[PYTHON] The performance of PHP was better than I expected

The beginning of that

I've been thinking about studying Python for a while recently. First of all, you write a program that outputs prime numbers to get a feel for it.

So, since it is a good idea, I compared the speed with C, PHP, JavaScript (Node.js), Python3.

version

C compiler

$ gcc --version
gcc (Ubuntu 8.3.0-6ubuntu1) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


PHP

$ php --version
PHP 7.2.19-0ubuntu0.19.04.1 (cli) (built: Jun  4 2019 14:44:42) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.19-0ubuntu0.19.04.1, Copyright (c) 1999-2018, by Zend Technologies

Node.js

$ node --version
v10.16.0

Python

$ python --version
Python 3.7.3

Source code

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>

int main()
{
    int maxNum = 65536;
    bool *a = (bool *)calloc(maxNum, sizeof(bool));
    a[2] = true;
    for (int i = 3; i < maxNum; i += 2) {
        bool p = true;
        int checkMax = (int)round(sqrt((double)i));
        for (int j = 2; j <= checkMax; ++j) {
            if (!a[j]) {
                continue;
            }
            if (i % j == 0) {
                p = false;
                break;
            }
        }
        if (p) {
            a[i] = true;
        }
    }
    for (int i = 2; i < maxNum; ++i) {
        if (a[i]) {
            printf("%d\n", i);
        }
    }
    return 0;
}

PHP

<?php

$maxNum = 65536;
$a = array_fill(0, $maxNum, false);
$a[2] = true;
for ($i = 3; $i < $maxNum; $i += 2) {
    $p = true;
    $checkMax = (int)round(sqrt((double)$i));
    for ($j = 2; $j <= $checkMax; ++$j) {
        if (!$a[$j]) {
            continue;
        }
        if ($i % $j === 0) {
            $p = false;
            break;
        }
    }
    if ($p) {
        $a[$i] = true;
    }
}
for ($i = 2; $i < $maxNum; ++$i) {
    if ($a[$i]) {
        printf("%d\n", $i);
    }
}

JavaScript

const maxNum = 65536;
const a = Array(maxNum);
a.fill(false);
a[2] = true;
for (let i = 3; i < maxNum; i += 2) {
    let p = true;
    const checkMax = parseInt(Math.round(Math.sqrt(parseFloat(i))));
    for (let j = 2; j <= checkMax; ++j) {
        if (!a[j]) {
            continue;
        }
        if (i % j === 0) {
            p = false;
            break;
        }
    }
    if (p) {
        a[i] = true;
    }
}
for (i = 2; i < maxNum; ++i) {
    if (a[i]) {
        console.log(i);
    }
}

Python

import math
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN

maxNum = 65536
a = [False] * maxNum;
a[2] = True
for i in range(3, maxNum, 2):
    p = True
    checkMax = int(Decimal(str(math.sqrt(i))).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
    for j in range(2, checkMax + 1):
        if not a[j]:
            continue
        if i % j  == 0:
            p = False;
            break;
    if p:
        a[i] = True;
for i in range(2, maxNum):
    if a[i]:
        print('%d' % i)

result

C The compilation is as follows. No optimization is specified.

$ gcc p.c -lm
$ time ./a.out > /dev/null
./a.out > /dev/null  0.02s user 0.00s system 76% cpu 0.021 total

PHP

$ time php p.php > /dev/null
php p.php > /dev/null  0.22s user 0.01s system 93% cpu 0.249 total

It takes 10 times as much as C. Node.js

$ time node p.js > /dev/null
node p.js > /dev/null  0.53s user 0.04s system 74% cpu 0.768 total

30 times C. Python

$ time python p.py > /dev/null
python p.py > /dev/null  0.77s user 0.02s system 77% cpu 1.020 total

50 times C.

Summary

So PHP was faster than anything else. This is unavoidable because C is the fastest.

By the way, the result of redirecting the output result to a file and finding the hash value is as follows.

$ md5sum *.txt
3c22247fa4a5c6a8b9009cfc70961f90  result_c.txt
3c22247fa4a5c6a8b9009cfc70961f90  result_js.txt
3c22247fa4a5c6a8b9009cfc70961f90  result_php.txt
3c22247fa4a5c6a8b9009cfc70961f90  result_python.txt
$ sha512sum *.txt
ae4a60fb2903b488179a36be80b5569153cc27a4989001af9015355fcd5ffa0ddd94cf64d0beeeaff4a51bd3cf8c8594d0d47379825b50a185d259840b20202c  result_c.txt
ae4a60fb2903b488179a36be80b5569153cc27a4989001af9015355fcd5ffa0ddd94cf64d0beeeaff4a51bd3cf8c8594d0d47379825b50a185d259840b20202c  result_js.txt
ae4a60fb2903b488179a36be80b5569153cc27a4989001af9015355fcd5ffa0ddd94cf64d0beeeaff4a51bd3cf8c8594d0d47379825b50a185d259840b20202c  result_php.txt
ae4a60fb2903b488179a36be80b5569153cc27a4989001af9015355fcd5ffa0ddd94cf64d0beeeaff4a51bd3cf8c8594d0d47379825b50a185d259840b20202c  result_python.txt

It seems that the same output was obtained for all. We have not actually verified whether it is correct as a list of prime numbers. Because it is a verification of how the execution speed is different with the same algorithm.

When it comes to parallel processing, PHP, which cannot be multithreaded by default, is disadvantageous.

Recommended Posts

The performance of PHP was better than I expected
I measured the performance of 1 million documents with mongoDB
I investigated the mechanism of flask-login!
I checked the options of copyMakeBorder of OpenCV
I summarized the folder structure of Flask
I didn't know the basics of Python
The Python project template I think of.
I read the implementation of golang channel
I was in trouble because the behavior of docker container did not change
P100-PCIE-16GB was added to the GPU of Google Colab before I knew it
AtCoder AGC 041 C --I was addicted to the full search of Domino Quality
Kaggle's feature management was better than I expected with PostgreSQL, so I created a directory that anyone can use with Docker.
I tried cluster analysis of the weather map
Summary of the differences between PHP and Python
The inaccuracy of Tensorflow was due to log (0)
I solved the deepest problem of Hiroshi Yuki.
I checked the list of shortcut keys of Jupyter
I tried to touch the API of ebay
I tried to correct the keystone of the image
Try the free version of Progate [Python I]
The shape of the one-dimensional array of numpy was complicated
I checked the session retention period of django
I checked the processing speed of numpy one-dimensionalization
I touched some of the new features of Python 3.8 ①
I read and implemented the Variants of UKR
I want to customize the appearance of zabbix
I tried using the image filter of OpenCV
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
Here is one of the apps with "artificial intelligence" that I was interested in.
I'm used to php + twig, so I changed the template engine of pyramid 1.5 to jinja2
[Python & SQLite] I analyzed the expected value of a race with horses with a win of 1x ②
[Probability] I will explain because the robot problem of Center 2020 Mathematics 1 ・ A was interesting.
When I used Plotly to draw an interactive graph, it was more than I expected.