📜 ⬆️ ⬇️

Honest PHP and Python speed testing

Good day.
We all know that the quality and speed of the code depends on the programmer. A good programmer can skillfully use the strengths and weaknesses of his PL.
The last time PHP showed its strong side - numbers are numbers. In Python, numbers are objects.
So for an objective test, you need PHP to also consider mathematical objects.

Testing method

Complex numbers are good mathematical objects, in PHP and Python complex numbers will be represented by objects. I took the test with a naive search for prime numbers and a code written by Thomas Vander Stichele , only real numbers from a complex number are used instead of integers. The main thing is that the condition is met that objects are used in two languages.

I tried to make the code more similar to each other in order to observe the objectivity of the test. Therefore, I did not use various tricky optimizations that I know for Python and I don’t know for PHP. In Python, there is a built-in class of complex numbers, but for the objectivity of the test, the class of complex numbers is written similar to the PHP version and with minimal functionality.

The resulting code is:
')
Php
#!/usr/bin/env php <?php class Complex { public $real = 0; private $imag = 0; public function __construct($real, $imag = null) { $this->real = (float)$real; } public function __toString() { return sprintf("(%d+%dj)", $this->real, $this->imag); } } $start = microtime(TRUE); $primeNumbers = array(); $output = ''; for ($i = 2; $i < 100000; $i++) { $divisible = false; $in = new Complex($i); foreach($primeNumbers as $number) { if ($in->real % $number->real == 0) { $divisible = true; break; } } if ($divisible == false){ $primeNumbers[] = $in; $output .= $in; } } echo "time: ", microtime(TRUE) - $start, "\n"; echo count($primeNumbers), " ", strlen($output), "\n"; ?> 


Python
 #!/usr/bin/env python import time class Complex(object): def __init__(self, real, imag=None): self.real = real self.imag = 0 def __str__(self): return "({0}+{1}j)".format(self.real, self.imag) start = time.time() primeNumbers = [] output = "" for i in xrange(2, 100000): divisible = False inum = Complex(i) for number in primeNumbers: if inum.real % number.real == 0: divisible = True break if divisible == False: primeNumbers.append(inum) output += str(inum) print 'time: %f' % (time.time() - start) print len(primeNumbers), len(output) 


Testing

In my test environment Ubuntu 10.04 running in VMWare Player 3 on a Celeron 1.2GHz processor, it turned out:

Conclusion

If you need a simple math calculator, use PHP.
In objective tests, Python is faster.

Thomas Vander Stichele also noted that with the help of the Eratosthenes sieve, the search for primes can be speeded up many times.

PS: I would be grateful if you specify where the code is not equivalent, only without tricky optimizations.

Hello everyone in the python-django-spb group, please join too.

Source: https://habr.com/ru/post/124346/


All Articles