Why is my perl script an order of magnitude faster than the equivalent python code

I recently took over Python3 and was shocked at how much slower it is than other comparable dynamic languages ​​(mostly Perl).

When trying to learn Python, I made a few online coding problems and Python was often at least 10x slower than Perl and used at least 2x memory.

While researching this curiosity, I came across people asking why Python is slower than C / C ++, which should be pretty obvious, but not any posts comparing it to other similar languages. There is also this informative but outdated test http://raid6.com.au/~onlyjob/posts/arena/

that confirms that it is quite slow.

I am explaining about standard Python implementation and NOT something like pypy or similar.

EDIT: The reason I was surprised comes from the results page at codeeval.com. Here are two scripts to use the first character of every word in a string.

Python3 (3.4.3) v1

import sys
import re

def uc(m):
    c = m.group(1)
    return c.upper()

f = open(sys.argv[1], "r")
for line in f:
    print(re.sub(r"\b(\D)", uc, line))

      

Perl (5.18.2)

use strict;
use warnings "all";

open(my $fh, "<", "$ARGV[0]") or die;
while (<$fh>)
{
    s,\b(\D),uc $1,ge;
    print;
}
close $fh;

      

Since I am not very familiar with Python, I also tried another version to see if there is any difference.

Python3 v2:

import sys

f = open(sys.argv[1], "r")
for line in f:
    lst = [word[0].upper() + word[1:] for word in line.split()]
    print(" ".join(lst))

      

The results are completely different as you can see in this image: https: // i.  imgur.com/3wPrFk5.png(The results for Python in this image are from v1, v2 had almost identical statistics (runtime +1 ms, ~ same memory usage)

+3


source to share





All Articles