>>27
Try a real application.
However, I was surprised at PHP 5's performance so I've done a more realistic test (n times more realistic than yours, n times less realistic than reality; n is a large number).
It consists of a function f(n) -> list of primes up to n, using a simple algorithm. It involves nested loops, simple Maths and list concatenation. Code available below results. Tested on Win32 for 500000 primes.
PHP 4.3.11: 17.078 s
Perl 5.8.7: 11.453 s
PHP 5.2.2RC2: 7.750 s
Python 2.4.2: 6.437 s
Python 2.4.2 + Psyco: 1.141 s
g++ 3.4.2 MinGW -O0: 0.625 s
g++ 3.4.2 MinGW -O3 -funroll-loops: 0.515 s
Important things to see:
1. PHP 5 has got a massive improvement in performance. Now it outperforms Perl, and it's closer to Python than it's to Perl.
2. Python is still the fastest.
3. Python + Psyco is half as fast as C++ for intensive computation, offering a language that's vastly more powerful and flexible, ridiculously more productive, and easier to learn.
4. CFLAGS JUST KICKED IN, YO!
-----------------------
Sauce:
PHP:
<?php
function Primes($max) {
for ($i = 1; $i <= $max; ++$i) {
$prime = true;
$limit = (int) sqrt($i);
for ($j = 2; $j <= $limit; ++$j)
if (!($i % $j)) {
$prime = false;
break;
}
if ($prime)
$a[] = $i;
}
return $a;
}
Primes(500000);
?>
Perl:
sub Primes {
@a = ();
$max = @_[0];
for ($i = 1; $i <= $max; ++$i) {
$prime = 1;
$limit = int(sqrt($i)) + 1;
for ($j = 2; $j < $limit; ++$j) {
if (!($i % $j)) {
$prime = 0;
last;
}
}
push @a, $i if $prime;
}
return @a;
}
Primes(500000);
Python:
from math import sqrt
def Primes(max):
a = []
for i in xrange(1, max + 1):
prime = True
for j in xrange(2, int(sqrt(i)) + 1):
if not i % j:
prime = False
break
if prime:
a += [i]
return a
Primes(500000)
C++ (by Anonymous):
#include <vector>
std::vector<int> primes(int max) {
std::vector<int> a;
int limit(1);
for (int i(1); i <= max; ++i) {
bool isPrime(true);
int newLimit = limit + 1;
if (newLimit * newLimit <= i) ++limit;
for (int j(2); j <= limit; ++j) {
if (!(i % j)) {
isPrime = false;
break;
}
}
if (isPrime) a.push_back(i);
};
return a;
}
int main() {
std::vector<int> v = primes(500000);
}