Experimenting with some code and doing some microbenchmarks I just found out that using the float
function on a string containing an integer number is a factor 2 faster than using int
on the same string.
>>> python -m timeit int('1')
1000000 loops, best of 3: 0.548 usec per loop
>>> python -m timeit float('1')
1000000 loops, best of 3: 0.273 usec per loop
It gets even stranger when testing int(float('1'))
which runtime is shorter than the bare int('1')
.
>>> python -m timeit int(float('1'))
1000000 loops, best of 3: 0.457 usec per loop
I tested the code under Windows 7 running cPython 2.7.6 and Linux Mint 16 with cPython 2.7.6.
I have to add that only Python 2 is affected, Python 3 shows a way smaller (not remarkable) difference between the runtimes.
I know that the information I get by such microbenchmarks are easy to misuse, but I'm curious why there is such a difference in the functions' runtime.
I tried to find the implementations of int
and float
but I can not find it in the sources.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…