Jason Nordwick wrote: > *mouth agape* > > Wow. That really sucks. I make extensive use of reduce. It seems to run more > than twice as fast as a for loop. > > >>> t = Timer('bino.reduceadd(bino.bits)', 'import bino') > >>> s = Timer('bino.loopadd(bino.bits)', 'import bino') > >>> t.timeit(10) > 1.2373670396656564 > >>> s.timeit(10) > 2.6450051612705039 > >>> t.timeit(100) > 11.312374896809501 > >>> s.timeit(100) > 25.817132345032689 > > where > > bits = map(lambda x:randint(0,1), xrange(1000000)) > > def reduceadd(v): > return reduce(add, v) > > def loopadd(v): > sum = 0 > for x in v: > sum = add(sum, x) > return sum > > > > (Yes, I know there are better ways to sum up a list, but I just wanted to > test the performance of the loop against reduce. In most of my reduce usages, > the function passed to reduce is much more complex.) [...]
Assuming Guido van Rossum is right and reduce() is only useful for arithmetic expressions (could you show an example where you use it else?), you could take advantage of more "built-ins". To spoiler the result of this, the loop-variant is slightly (in this test: 2ms) faster. The results on my amd64 3k+ were: Reduce: 0.5686828074520.56633643382 For-loop: 0.56633643382 #!/usr/bin/env python # # from random import randint from timeit import Timer from operator import add def bits(): return [randint(0,1) for x in xrange(1000)] # use def & list comprehension since lambda/map will be removed in Python 3.0, too print bits()[0:5] print bits()[0:5] # it's working. def reducefunc(x): return reduce(add,x) def loopfunc(x): y = 0 for i in x: y += i return y x = bits() print reducefunc(x) print loopfunc(x) # both give proper output print sum(Timer("reducefunc(bits())", "from __main__ import bits, reducefunc").repeat(20,100))/20 print sum(Timer("loopfunc(bits())", "from __main__ import bits, loopfunc").repeat(20,100))/20 -- http://mail.python.org/mailman/listinfo/python-list