I want to understand why the first example took twice as long than the second one. My intuition says that converting integer chars to int
should be atleast as fast as converting them to float
, if not faster.
>>> from timeit import timeit
>>> timeit("float(sum(map(int,['5', '8', '3', '6', '3', '9', '5', '0', '1', '0'])))")
6.165183067321777
>>> timeit("sum(map(float, ['5', '8', '3', '6', '3', '9', '5', '0', '1', '0']))")
2.928786039352417
edit: duplicate of Why is float() faster than int()?
even the presence of extra float
call in the first example is not the cause because I ran timeit for it as well and it takes 1% time as compared to these operations (for same number)
>>> from timeit import timeit
>>> timeit("float(sum(map(int,['5', '8', '3', '6', '3', '9', '5', '0', '1', '0']
)))", number=100000)
0.6287150382995605
>>> timeit("sum(map(float, ['5', '8', '3', '6', '3', '9', '5', '0', '1', '0']))"
,number=100000)
0.2976219654083252
>>> timeit("float(1)",number=100000)
0.02610301971435547
I tried dis
, but nothing there helped me either:
def a(li):
return float(sum(map(int,li)))
def b(li):
return sum(map(float, li))
# >>> dis(a)
# 4 0 LOAD_GLOBAL 0 (float)
# 3 LOAD_GLOBAL 1 (sum)
# 6 LOAD_GLOBAL 2 (map)
# 9 LOAD_GLOBAL 3 (int)
# 12 LOAD_FAST 0 (li)
# 15 CALL_FUNCTION 2
# 18 CALL_FUNCTION 1
# 21 CALL_FUNCTION 1
# 24 RETURN_VALUE
# >>> dis(b)
# 4 0 LOAD_GLOBAL 0 (sum)
# 3 LOAD_GLOBAL 1 (map)
# 6 LOAD_GLOBAL 2 (float)
# 9 LOAD_FAST 0 (li)
# 12 CALL_FUNCTION 2
# 15 CALL_FUNCTION 1
# 18 RETURN_VALUE
I was using python 2.7.12 for this test