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.
In theory, the fastest possible operation takes one CPU cycle, to it boils down to saying that multiplying floating point numbers is every bit as fast as adding integers. The complexity of the algorithm hasn't gone away, so this is absolutely stunning.
An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
7 Answers. Show activity on this post. Well, here's a quick explanation: An int and float usually take up "one-word" in memory.
Arithmetic on int s is much faster. int s will never suffer from precision loss. People reading your code will know that the variable is actually an integer.
int
has lots of bases.
*, 0*, 0x*, 0b*, 0o* and it can be long, it takes time to determine the base and other things
if the base is set, it saves a lot of time
python -m timeit "int('1',10)" 1000000 loops, best of 3: 0.252 usec per loop python -m timeit "int('1')" 1000000 loops, best of 3: 0.594 usec per loop
as @Martijn Pieters metions the code the Object/intobject.c(int_new)
and Object/floatobject.c(float_new)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With