sum() vs. loop
Steve Keller
keller.steve at gmx.de
Sun Oct 10 04:49:50 EDT 2021
I have found the sum() function to be much slower than to loop over the
operands myself:
def sum_products(seq1, seq2):
return sum([a * b for a, b in zip(seq1, seq2)])
def sum_products2(seq1, seq2):
sum = 0
for a, b in zip(seq1, seq2):
sum += a * b
return sum
In a program I generate about 14 million pairs of sequences of ints each
of length 15 which need to be summed. The first version with sum() needs
44 seconds while the second version runs in 37 seconds.
Can someone explain this difference?
Steve
More information about the Python-list
mailing list