Python 2 times slower than Perl

Gareth McCaughan Gareth.McCaughan at pobox.com
Thu Jul 19 19:58:26 EDT 2001


Xu, C.S. wrote:

> Just spent a little time to compare 4 stupid again algorithms
> (changed a little bit from last time) for both python and perl
> (codes attached) on two systems (SunOS and Linux):

[SNIP: tight loop of floating-point adds and multiplies]

If that's what your code spends all its time doing, then
by all means use Perl instead of Python for it. Other
microbenchmarks may show different results, however.
For instance:

    #!/usr/bin/perl

    @d = ();
    for $i (0..499999) { $d{$i} = $i; }
    print $d[499999], "\n";

takes 2.32 seconds to run on my machine, whereas

    #!/usr/local/bin/python

    d = {}
    for i in range(500000): d[i]=i
    print d[499999]

takes 1.15 seconds. Aha! "Perl 2 times slower than Python".
Using xrange instead of range improves that to 1.07 seconds.
Changing the Perl program to use a "C-style" for-loop
makes it much slower, by the way.


Or, since you're apparently interested in numerics, how
about some multiple-precision arithmetic?

    #!/usr/bin/perl

    use Math::BigInt;

    $f = new Math::BigInt '1';
    for $i (1..1000) { $f=$f*$i; }
    print $f;

takes 5.2 seconds.

    #!/usr/local/bin/python

    f=1L
    for i in range(1,1001): f=f*i
    print f

takes 0.07 seconds. That's more than a factor of 7 in Python's
favour.


On the other hand, in another microbenchmark I just tried (count
the number of occurrences of every word in a file, then print
them in descending order of frequency) Perl comes out about
twice the speed of Python, and I don't see any obvious way to
improve Python's speed on this.


Does this prove that Python is faster than Perl, or that Perl
is faster than Python? Nope. It proves that benchmarks like this
don't prove anything, one way or the other.


(All timings are approximate. My machine is a 1GHz Athlon
running FreeBSD. Perl version 5.00503, Python version 2.1.)

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc



More information about the Python-list mailing list