将一个整数转换为浮点数的原因是什么慢于在Python中为该int添加0.0?
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)
其输出为:
Add simple timing: 0.0001220703125
Cast simple timing: 0.000469923019409
Add total timing: 0.000164985656738
Cast total timing: 0.00040078163147
解决方法
如果您使用dis模块,您可以开始看到为什么:
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
注意CALL_FUNCTION