CythonとPythonとの処理時間の比較
Pythonを高速化するCythonを使ってみた - Kesin's diary
ここに書いてあることがおもしろそうだったのでやってみた.
1~100000000まで足しこむプログラム. 環境はmacで。
C
#include <stdio.h> int main(){ int i,n=0; for(i=0;i<100000000;i++) n+=i; }
オプションで最適化しとく.
gcc -O2 a.c
time ./a.out ./a.out 0.00s user 0.00s system 31% cpu 0.007 total
うん。速い。
Python
n=0 for i in range(100000000): n += i
同じく
time python3 add.py python add.py 13.15s user 1.53s system 97% cpu 15.021 total
遅い.
型指定していないCython
def add_test(): n=0 for i in range(100000000): n+=i
で、setup.pyを
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension("add", ["add.pyx"])] setup( name = 'Hello world app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
として,main.pyを以下の通りに作成して
from add import add_test add_test()
として実行すると
time python3 main.py python3 main.py 5.75s user 0.02s system 99% cpu 5.830 total
だいぶ速くなった!
型指定したCython
def add_test(): cdef int n = 0 cdef int i for i in range(100000000): n+=i
あとはさっきと同様にして実行
time python3 main.py python3 main.py 0.03s user 0.01s system 68% cpu 0.064 total
速すぎわろた。
グラフにすると
こんな感じ.