Optimizations (was Re: reduce vs. for loop)
Gustavo Cordova
gcordova at hebmex.com
Tue Mar 26 10:49:25 EST 2002
>
> > >Just out curiosity,
> > >why is fact2 a bit faster than fact1?
> > >
> > >def fact1(n):
> > > return reduce (operator.mul, range(1L,n + 1))
> > >
> > >def fact2(n):
> > > result = n * 1L
> > > for i in range(1 , n):
> > > result *= i
> > > return result
> >
> > Try this:
> >
> > def fact3(n):
> > mul = operator.mul
> > return reduce(mul, range(1L, n+1) )
>
> operator.mul will be evaluated only once in even in fact1, so this
> shouldn't make any difference.
>
> Just
And I re-ran the tests using the normal functions, and then
again after applying psyco.bind() to them. Here's the times
with n=10000:
===== TEST PRINTOUT =====
Running factorial tests (n=10000)
fact1: 5.16 seconds.
fact2: 4.73 seconds.
fact3: 4.78 seconds.
** Applying psyco.bind()
** Rerunning tests.
psyco: sys._getframe() not supported; support for warnings is only partial
fact1: 4.77 seconds.
fact2: 4.45 seconds.
fact3: 4.78 seconds.
Press <enter> to quit.
=========================
Oh well.
:-)
-gustavo
More information about the Python-list
mailing list