3 ms·
That sure surprised me, I would have rooted for reduce. May be lambda overhead is screwing it up. Could you try the reduction with from operator import add
by srean 12y ago
That sure surprised me, I would have rooted for reduce. May be lambda overhead is screwing it up. Could you try the reduction with
from operator import add
I cannot try it out on Colin's version of Python, however on
Python 2.7.6 | 32-bit |
[GCC 4.1.2 20080704]
from operator import add
def sum1(l): return reduce(lambda a,b:a+b,l)
def sum2(l): return reduce(add,l)
The times to compute sum1(l) and sum2(l) on xrange(3333333) are
11.69s and
6.38s
respectively.
So sum2 is about twice faster, which is expected. The timings are the minimum of 5 runs. Given Colin's reduce was about twice slower than his for loop, there is a fair chance that the updated reduce will beat the for loop occasionally.
I was surprised that trying the same on an array turned out to be marginally slower than using an xrange. I would have expected the array to be faster. xrange is possibly faster because it can be held in cache whereas the array would definitely spill outside, although I expected locality to be a win.