Skip to content
Advertisement

Why is PHP7 so much faster than Python3 in executing this simple loop?

As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.

Python’s execution time was horrible in comparison to PHP’s (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Python? Is there something I’m doing wrong, or some optimizations/settings that would improve its performance to meet or exceed that of PHP? Or is Python just that much slower (surely not!)?

Yes I saw this benchmark, which reports PHP 7 blazes past the other languages, but you’d think both would be fairly equally optimized when doing such a simple operation.

Python executes the loop about twice as fast if a string assignment is substituted for the addition. But that’s still 34 seconds vs about 1.1 sec.

PHP7 code:

<?php

function test($x)
{
    $t1 = microtime(true);
    $a = 0;
    for($i = 0; $i < $x; $i++)
    {
        $a++;
    }
    $t2 = microtime(true);

    echo "Time for $x was " . ($t2 - $t1) . "n";

    return $a;
}


echo test(100000);
echo test(1000000);
echo test(10000000);

Results: Time for 100000 was 0.036377191543579 100000Time for 1000000 was 0.18501400947571 1000000Time for 10000000 was 1.3939099311829

Python3 code:

import time
def test(x):
    t1 = time.clock()
    a = 0
    for i in range(x):
        a += 1
    t2 = time.clock()
    print("Time for {} was {}".format(x, t2 - t1))
    return x

print(test(1000000))
print(test(10000000))
print(test(100000000))

Results: Time for 1000000 was 0.761641 1000000 Time for 10000000 was 7.427618000000001 10000000 Time for 100000000 was 74.320387 100000000

UPDATE: yes after @Amber pointed it out, I realize I totally PEBKAKed and the loop counters are an order of magnitude apart. Even so, the answers were really interesting so it was worth asking the question.

Advertisement

Answer

They’re both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:

PHP: https://ideone.com/3ebkai 2.7089s

<?php

function test($x)
{
    $t1 = microtime(true);
    $a = 0;
    for($i = 0; $i < $x; $i++)
    {
        $a++;
    }
    $t2 = microtime(true);

    echo "Time for $x was " . ($t2 - $t1) . "n";

    return $a;
}


echo test(100000000);

Python: https://ideone.com/pRFVfk 4.5708s

import time
def test(x):
    t1 = time.clock()
    a = 0
    for i in range(x):
        a += 1
    t2 = time.clock()
    print("Time for {} was {}".format(x, t2 - t1))
    return x

print(test(100000000))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement