Debugging reason for python running unreasonably slow when adding numbers

Chris Angelico rosuav at gmail.com
Wed Mar 15 11:01:36 EDT 2023


On Thu, 16 Mar 2023 at 01:26, David Raymond <David.Raymond at tomtom.com> wrote:
> I'm not quite sure why the built-in sum functions are slower than the for loop,
> or why they're slower with the generator expression than with the list comprehension.

For small-to-medium data sizes, genexps are slower than list comps,
but use less memory. (At some point, using less memory translates
directly into faster runtime.) But even the sum-with-genexp version is
notably faster than reduce.

Is 'weights' a dictionary? You're iterating over it, then subscripting
every time. If it is, try simply taking the sum of weights.values(),
as this should be significantly faster.

ChrisA


More information about the Python-list mailing list