yet another noob question

Jason Nordwick jason at adapt.com
Mon Aug 14 15:03:05 EDT 2006


*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.)
-j


bearophileHUGS at lycos.com wrote:
> Jason Nordwick:
>> Stargaming wrote:
>>> Also note that reduce will be removed in Python 3000.
>> What will replace it?
> 
> Nothing, I presume. You will have to write a function to find another
> way to solve problems.
> 
> Bye,
> bearophile
> 




More information about the Python-list mailing list