Why is PHP7 so much faster than Python3 in executing this simple loop?
You guys are not being fair. The two pieces of code are NOT doing the same thing.
While PHP only increments two variables ($a and $i), Python is generating a range before it loops.
So, to have a fair comparison your Python code should be:
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
Aaaaaaand, it's MUCH faster:
>>> print(test(100000000))
Time for 100000000 was 6.214772
VS
>>> print(test2(100000000))
Time for 100000000 was 3.079545
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))