casting - Why is calling float() on a number slower than adding 0.0 in Python? -
what reason casting integer float slower adding 0.0 int in python?
import timeit def add_simple(): in range(1000): = 1 + 0.0 def cast_simple(): in range(1000): = float(1) def add_total(): total = 0 in range(1000): total += 1 + 0.0 def cast_total(): total = 0 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 is:
add simple timing: 0.0001220703125
cast simple timing: 0.000469923019409
add total timing: 0.000164985656738
cast total timing: 0.00040078163147
if use dis
module, can start 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 call_function
function calls in python (relatively) slow. .
lookups. because casting float
requires function call - that's why it's slower.
Comments
Post a Comment