strange sum behavior

jepler80 at unpythonic.net jepler80 at unpythonic.net
Sun Feb 22 10:51:56 EST 2004


I get similar results from
Python 2.4a0 (#1, Feb 19 2004, 17:19:10) 
[GCC 3.3.2 20031022 (Red Hat Linux 3.3.2-1)] on linux2

$ timeit -s 'l=range(0,1000000)' 'sum(l)'
10 loops, best of 3: 985 msec per loop
$ timeit -s 'l=range(0,1000000)' 'sum([sum(l[x:x+1000]) for x in xrange(0,len(l),1000)])'
10 loops, best of 3: 352 msec per loop

I suspect the reason is that the top loop has many operations on Python
longs (unbounded ints), while the bottom loop has relatively few.  Here's a
use of sum() that doesn't switch from ints to longs:
$ timeit -s 'l=[0]*1000000' 'sum(l)'
10 loops, best of 3: 241 msec per loop
$ timeit -s 'l=[0]*1000000' 'sum([sum(l[x:x+1000]) for x in xrange(0,len(l),1000)])'
10 loops, best of 3: 285 msec per loop

... the nested loop is slower, as it should be.

Jeff




More information about the Python-list mailing list