Speed of Python

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Sep 8 02:27:44 EDT 2007


On Fri, 07 Sep 2007 23:53:48 +0000, wang frank wrote:

>>From: "Marc 'BlackJack' Rintsch" <bj_666 at gmx.net>
>>To: python-list at python.org
>>Subject: Re: Speed of Python
>>Date: 7 Sep 2007 23:17:55 GMT
>>
>>On Fri, 07 Sep 2007 22:59:26 +0000, wang frank wrote:
>>
>> > I also have tried to use numpy to speed it up. However, surprisingly, 
> it is
>> > slower than the pure python code.
>> >
>> > Here is the code:
>> > import  numpy
>> > arange=numpy.arange
>> > nlog=numpy.log
>> > def bench6(n):
>> > 	for i in xrange(n):
>> > 		for j in xrange(1000):
>> > 			m=j+1
>> > 			z=nlog(m)
>> > 			z1=nlog(m+1)
>> > 			z2=nlog(m+2)
>> > 			z3=nlog(m+3)
>> > 			z4=nlog(m+4)
>> > 			z5=nlog(m+5)
>> > 			z6=nlog(m+6)
>> > 			z7=nlog(m+7)
>> > 			z8=nlog(m+8)
>> > 			z9=nlog(m+9)
>> > 	return z9
>> >
>> > [窶ヲ]
>> >
>> > Anyone know why?
>>
>>Because you don't really take advantage of `numpy`.  The `numpy.log()`
>>function can be used with scalars but I guess it is slower because it has
>>to check if its argument is a scalar or array.  Untested:
>>
>>from numpy import arange, log as nlog
>>
>>def bench6(n):
>>     for dummy in xrange(n):
>>         for j in xrange(1000):
>>             z = nlog(arange(j + 1, j + 11))
>>     return z[-1]
>
> I am just trying to compare the speed with matlab. The arrange is used for 
> another test, that is why it shows up in the mail.

I think I don't get what you are after.  If you want to compare the speed
of code that *calculates* the same values it doesn't have to *look* the
same.  So what's the point of importing `numpy` and its `log` function if
you don't write the code in a fashion that takes advantage of the package
at all!?

And the other "pure" Python versions may gain some speed if you think
Python and not Matlab with Python syntax.  That might look like this:

from math import log

def bench42(n):
    the_range = xrange(1, 1001)
    for dummy in xrange(n):
        for i in the_range:
            z = [log(x) for x in xrange(i, i + 10)]
    return z[-1]

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list