为什么PHP7在执行这个简单循环时比Python3快得多?

Rya*_*ggs 10 php python performance

作为一个非常简单的基准测试,我在同一个Raspberry Pi 3模型B上执行了PHP 7.0.19-1和Python 3.5.3(命令行)上面的简单代码.

与PHP相比,Python的执行时间非常糟糕(74秒对1.4秒).任何人都可以帮助我理解为什么执行在Python上需要这么长时间?有什么我做错了,或者一些优化/设置可以提高其性能以达到或超过PHP的性能?或者Python的速度要慢得多(当然不是!)?

是的,我看到了这个基准测试,它报告了PHP 7超越其他语言,但你认为在进行这样一个简单的操作时两者都会得到相当优化.

如果用字符串赋值代替添加,Python执行循环的速度大约快两倍.但这仍然是34秒vs 1.1秒.

PHP7代码:

<?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);
Run Code Online (Sandbox Code Playgroud)

结果:100000的时间为0.036377191543579 100000时间1000000为0.18501400947571 1000000时间为10000000为1.3939099311829

Python3代码:

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))
Run Code Online (Sandbox Code Playgroud)

结果:1000000的时间为0.761641 1000000 10000000的时间为7.427618000000001 10000000 1亿的时间为74.320387 1亿

Amb*_*ber 10

当你以相同的周期计数运行它们而不是让Python计数大一个数量级时,它们都在彼此的数量级内:

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);
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)


Raf*_*kel 5

你们不公平。这两段代码没有做相同的事情。

虽然PHP仅增加两个变量($ a和$ i),但Python在循环之前会生成一个范围。

因此,为了进行公平的比较,您的Python代码应为:

import time
def test2(x):
    r = range(x) #please generate this first
    a = 0

    #now you count only the loop time
    t1 = time.clock()
    for i in r:
        a += 1
    t2 = time.clock()

    print("Time for {} was {}".format(x, t2 - t1))
    return a
Run Code Online (Sandbox Code Playgroud)

Aaaaaaand,速度要快得多:

>>> print(test(100000000))
Time for 100000000 was 6.214772
Run Code Online (Sandbox Code Playgroud)

VS

>>> print(test2(100000000))
Time for 100000000 was 3.079545
Run Code Online (Sandbox Code Playgroud)