sum() vs. loop
Christian Gollwitzer
auriocus at gmx.de
Sun Oct 10 05:28:54 EDT 2021
Am 10.10.21 um 10:49 schrieb Steve Keller:
> 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.
The first version constructs a list, sums it up and throws the list
away, while the second version only keeps the running sum in memory. How
about a generator expression instead, i.e.
sum((a * b for a, b in zip(seq1, seq2)))
(untested) ?
Christian
More information about the Python-list
mailing list