Why these two approaches for computing sum produce different run-time? (5 times check) Both codes run on : https://colab.research.google.com
from timeit import repeat
setup = 'a = [1] * 10_000_000'
expressions = [
'sum(x % 2 for x in a)',
'sum(True for x in a if x % 2)',
]
for expression in expressions:
times = sorted(repeat(expression, setup, number=1))
print(*('%.2f ' % t for t in times), expression)
result:
0.65 0.65 0.65 0.65 0.66 sum(x % 2 for x in a)
1.03 1.04 1.04 1.05 1.06 sum(True for x in a if x % 2)
Another check but different result:
...
setup = 'a = [0] * 10_000_000'
...
Result:
0.66 0.66 0.66 0.67 1.45 sum(x % 2 for x in a)
0.43 0.43 0.44 0.45 0.46 sum(True for x in a if x % 2)
Third check
...
setup = 'a = range(10**7)'
...
Result:
0.75 0.75 0.76 0.77 0.78 sum(x % 2 for x in a)
0.81 0.82 0.82 0.82 0.84 sum(True for x in a if x % 2)