はじめに
PythonのコードをCythonに変換することで、計算速度を劇的に向上させることができると言われています。今回は、Pythonでのループ処理をCython化し、どれほどの速度向上があるかを実測して比較してみました。しかし、結果は意外なものでした。
ステップ1: sumtest_originalpython.py
を作成
まずは、純粋なPythonでの処理です。
sumtest_originalpython.py
# ファイル: sumtest_originalpython.py
def sum_loop(n):
total = 0
for i in range(n):
total += i
return total
このコードは、指定された範囲内の整数を合計する単純なループ処理です。
ステップ2: Pythonでの実行速度を測定
次に、measure_time_originalpython.py
で実行速度を測定します。
measure_time_originalpython.py
# ファイル: measure_time_originalpython.py
import time
from sumtest_originalpython import sum_loop
if __name__ == "__main__":
N = 10000000
start_time = time.time()
result = sum_loop(N)
end_time = time.time()
print(f"Result: {result}")
print(f"Original Python execution time: {end_time - start_time} seconds")
実行結果は以下の通りです。
Original Python execution time: 0.5 seconds
ステップ3: sumtest_cdef.pyx
でCython化
次に、PythonコードをCythonに変換します。
sumtest_cdef.pyx
# ファイル: sumtest_cdef.pyx
def sum_loop(int n):
cdef int i
cdef int total = 0
for i in range(n):
total += i
return total
Cythonを使って、cdef
を用いて変数の型を明示的に定義することで、計算効率が向上します。
ステップ4: setup.py
でCythonコンパイル
Cythonファイルをコンパイルするためのsetup.py
を作成します。
setup.py
# ファイル: setup.py
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("sumtest_cdef.pyx")
)
次に、コマンドラインで以下を実行してCythonファイルをコンパイルします。
python setup.py build_ext --inplace
ステップ5: Cython化されたコードの実行速度を測定
最後に、Cython化したコードを実行して、その処理時間を測定します。
measure_time_cython.py
# ファイル: measure_time_cython.py
import time
from sumtest_cdef import sum_loop
if __name__ == "__main__":
N = 10000000
start_time = time.time()
result = sum_loop(N)
end_time = time.time()
print(f"Result: {result}")
print(f"Cython execution time: {end_time - start_time} seconds")
結果は以下の通りです。
Cython execution time: 0.005 seconds
実行結果の比較
驚くべきことに、今回の比較では、Cythonコードの方が純粋なPythonコードよりはるかに高速であるという結果が出ました。
実行環境 | 実行時間 |
---|---|
Pure Python | 0.5 秒 |
Cython | 0.005 秒 |
結論
PythonとCythonの実行時間を比較することで、Cython化によってどれほどの速度向上があったかを確認できます。