Debugging reason for python running unreasonably slow when adding numbers
Weatherby,Gerard
gweatherby at uchc.edu
Wed Mar 15 13:09:52 EDT 2023
Sum is faster than iteration in the general case.
Lifting a test program from Stack Overflow https://stackoverflow.com/questions/24578896/python-built-in-sum-function-vs-for-loop-performance,
import timeit
def sum1():
s = 0
for i in range(1000000):
s += i
return s
def sum2():
return sum(range(1000000))
print('For Loop Sum:', timeit.timeit(sum1, number=100))
print( 'Built-in Sum:', timeit.timeit(sum2, number=100))
---
For Loop Sum: 7.726335353218019
Built-in Sum: 1.0398506000638008
---
From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of David Raymond <David.Raymond at tomtom.com>
Date: Wednesday, March 15, 2023 at 11:46 AM
To: python-list at python.org <python-list at python.org>
Subject: RE: Debugging reason for python running unreasonably slow when adding numbers
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***
> Then I'm very confused as to how things are being done, so I will shut
> up. There's not enough information here to give performance advice
> without actually being a subject-matter expert already.
Short version: In this specific case "weights" is a 5,147 element list of floats, and "input" is a 10 element list of integers which has the indexes of the 10 elements in weights that he wants to add up.
sum_ = 0
for key in input:
sum_ += weights[key]
vs
sum_ = sum(weights[key] for key in input)
vs... other ways
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ikhJJxqJnllDHh6JKaMX8g2K-Ceq6ZiRDJxX7AbS-1AiBIrdAmA2qjBtYZbxel2mktyno1s9iJGo_zAl5alBIWxoVXE$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ikhJJxqJnllDHh6JKaMX8g2K-Ceq6ZiRDJxX7AbS-1AiBIrdAmA2qjBtYZbxel2mktyno1s9iJGo_zAl5alBIWxoVXE$>
More information about the Python-list
mailing list