On Mon, Oct 11, 2021 at 2:54 PM Steve Keller <keller.st...@gmx.de> wrote:
> 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? > I can't explain it. It might help to try a line-by-line profiler. If you need speed, maybe try Cython, numpy and/or numba. It seems like the generator expression should be the fastest to me. But writing for speed instead of writing for clarity is usually not a great idea. -- https://mail.python.org/mailman/listinfo/python-list