Perl code 37 times quickly than Python code??

Andrew Dalke dalke at dalkescientific.com
Wed Jan 16 02:21:03 CET 2002


Kirill Simonov wrote in message ...
>On Tue, Jan 15, 2002 at 11:53:49AM -0800, Toni Gaya wrote:

>> but Python program execution is 37 times long that Perl program. What
>> is WRONG??
>
>Your Perl program. You use the same variable $i in the inner and the
>outer loops.

Good catch!  I ran the sample perl code and got
0.080u 0.010s 0:00.09 100.0%    0+0k 0+0io 198pf+0w

I then inserted 'my($i);' in this bit of code to change

> sub Ramp {
> local (*result, $size, $start, $end) = @_;
>     $step = ($end-$start)/($size-1);

into this
> sub Ramp {
> local (*result, $size, $start, $end) = @_;
> my($i);
>    $step = ($end-$start)/($size-1);

and got
3.758u 0.007s 0:03.77 99.4%     0+0k 0+0io 198pf+0w

which is a factor of 47 slower.  The given Python code
on my box runs with
3.902u 0.017s 0:04.33 90.3%     0+0k 0+0io 234pf+0w

or about 4% slower than the perl code.  Replace the innermost
'xrange' with a 'range' (which is faster than xrange unless
N is rather large, and 'range' is the standard idiom) and I get:
3.766u 0.027s 0:03.80 99.4%     0+0k 0+0io 234pf+0w

So now 0.2% slower.


With a bit of funky caching,

_cache = None
_cache_size = None

def Ramp(result, size, start, end):
     global _cache, _cache_size
     step = (end-start)/(size-1)
     if size != _cache_size:
         _cache = range(size)
         _cache_size = size
     for i in _cache:
         result[i] = start + step*i

I get
3.233u 0.017s 0:03.26 99.3%     0+0k 0+0io 234pf+0w
which is 16% faster than perl.

                    Andrew
                    dalke at dalkescientific.com







More information about the Python-list mailing list