Home > Archives > 25 July 2017

25 July 2017

Python は遅いのか?

フィボナッチ数の計算で C の 70倍遅いとかいうことを聞いて,何となく今までの体感と違かったので手元で測ってみた.PyPy だけど.

プログラム達:

#include
int fib(int n) {
	if(n  <= 1) return 1;
	return fib(n-1)+fib(n-2);
}
int main(int argc, char *argv[])
{
	printf("%d\n", fib(42));
	return 0;
}
def fib(n):
	if n  <= 1:
		return 1
	else:
		return fib(n-1)+fib(n-2)
print(fib(42))

結果:

hogehoge:~/work/pypytest$ gcc -O3 -o fib fib.c
hogehoge:~/work/pypytest$ time ./fib
433494437
 
real    0m0.902s
user    0m0.900s
sys    0m0.000s
hogehoge:~/work/pypytest$ time pypy fib.py
433494437
 
real    0m9.285s
user    0m9.240s
sys    0m0.044s 

もう一回:

hogehoge:~/work/pypytest$ time ./fib
433494437
 
real    0m0.883s
user    0m0.880s
sys    0m0.000s
hogehoge:~/work/pypytest$ time pypy fib.py
433494437
 
real    0m9.429s
user    0m9.372s
sys    0m0.056s 

10倍? 大体このくらいな気がする.

それぞれの --version の結果:

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 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.
 
Python 2.7.10 (5.1.2+dfsg-1~16.04, Jun 16 2016, 17:37:42)
[PyPy 5.1.2 with GCC 5.3.1 20160413]

Home > Archives > 25 July 2017

Search
Feeds

Page Top