What is the reason that casting an integer to a float is slower than adding 0.0 to that int in Python?
import timeit
def add_simple():
for i in range(1000):
a = 1 + 0.0
def cast_simple():
for i in range(1000):
a = float(1)
def add_total():
total = 0
for i in range(1000):
total += 1 + 0.0
def cast_total():
total = 0
for i in range(1000):
total += float(1)
print "Add simple timing: %s" % timeit.timeit(add_simple, number=1)
print "Cast simple timing: %s" % timeit.timeit(cast_simple, number=1)
print "Add total timing: %s" % timeit.timeit(add_total, number=1)
print "Cast total timing: %s" % timeit.timeit(cast_total, number=1)
The output of which is:
Add simple timing: 0.0001220703125
Cast simple timing: 0.000469923019409
Add total timing: 0.000164985656738
Cast total timing: 0.00040078163147
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.
In that case the float value containing variable may contain same data but reason behind is to mathematical rules. The only two value are consider after the point & remaining are value get neglected. so the we get two different addresses of the same data containing variables.
Use numpy.arange() Pass float numbers to its start, stop, and step argument. For example, np. arange(0.5, 6.5, 1.5) will return the sequence of floating-point numbers starting from 0.5 up to 6.5.
Jul 23, 2020. The Python float() method converts a number stored in a string or integer into a floating point number, or a number with a decimal point. Python floats are useful for any function that requires precision, like scientific notation. Programming languages use various data types to store values.
If you use the dis
module, you can start to see why:
In [11]: dis.dis(add_simple)
2 0 SETUP_LOOP 26 (to 29)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (1000)
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
12 GET_ITER
>> 13 FOR_ITER 12 (to 28)
16 STORE_FAST 0 (i)
3 19 LOAD_CONST 4 (1.0)
22 STORE_FAST 1 (a)
25 JUMP_ABSOLUTE 13
>> 28 POP_BLOCK
>> 29 LOAD_CONST 0 (None)
32 RETURN_VALUE
In [12]: dis.dis(cast_simple)
2 0 SETUP_LOOP 32 (to 35)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (1000)
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
12 GET_ITER
>> 13 FOR_ITER 18 (to 34)
16 STORE_FAST 0 (i)
3 19 LOAD_GLOBAL 1 (float)
22 LOAD_CONST 2 (1)
25 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
28 STORE_FAST 1 (a)
31 JUMP_ABSOLUTE 13
>> 34 POP_BLOCK
>> 35 LOAD_CONST 0 (None)
38 RETURN_VALUE
Note the CALL_FUNCTION
Function calls in Python are (relatively) slow. As are .
lookups. Because casting to float
requires a function call - that's why it's slower.
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