Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is float() faster than int()?

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.

like image 721
halex Avatar asked Jan 20 '14 11:01

halex


People also ask

What is faster float or int?

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.

Is float better than int?

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.

Do floats use more memory than ints?

7 Answers. Show activity on this post. Well, here's a quick explanation: An int and float usually take up "one-word" in memory.

What is the main advantage of ints over floats?

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.


1 Answers

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)

like image 71
michaeltang Avatar answered Sep 28 '22 03:09

michaeltang