1
4

CythonでPythonコードを高速化する。

Last updated at Posted at 2024-01-04

1.初めに

Cythonを利用して、自分が書いたNumpyコードをどこまで高速化できるかを確認します。

2.Cythonと評価関数の準備

2.0. Cythonのインストール

Cythonをインストールします。

setup
pip install Cython

2.1. Pure Pythonの評価関数

評価用の関数を作成します。0からNまでの和を計算する単純な関数です。
純粋なPythonで関数を作成します。

test_function.py
def sum1(n):
    sum = 0
    for i in range(n):
        sum += i
    return sum

2.2. Cython形式の評価関数

Cythonのため、pyxのコードを作成します。結果が大きくなるので、intを使うとoverflowが発生します。そのため、longを使います。

test_function_cython.pyx
# test_function_cython.pyx
def sum2(int n):
    #cdef int i, sum = 0
    cdef long long i, sum = 0
    for i in range(n):
        sum += i
    return sum

3.Cythonコードをビルドする。

このCythonコードをビルドするためのセットアップファイルを作成します。

setup.py
from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("test_function_cython.pyx")
)

ビルドを実行して、Cythonモジュールを生成します。

setup
python setup.py build_ext --inplace

実行時間の計測

time_measurement_main.py
# https://youtu.be/T-ddo2V1HZE?si=beD-3RBQUSz5ExX0

from test_function import sum1
from test_function_cython import sum2
import time

if __name__ == "__main__":
    N = 10000000

    start = time.time()
    i = sum1(N)
    end = time.time()
    print(f'Pure python time is {str(end-start)} seconds')
    time1 = end-start
    print(str(i))
    print(N)
    start = time.time()
    i = sum2(N)
    end = time.time()
    print(f'Cython time is {str(end - start)} seconds')
    time2 = end-start
    print(str(i))

    print(f'Cython is faster than pure python by {round(time1/time2,0)} times.')
    print(f'Cython is faster than pure python by {round(time1 / time2, 2)} times.')

Cythonのほうが200倍以上速いです。

result

Pure python time is 0.5340635776519775 seconds
49999995000000
10000000
Cython time is 0.0019910335540771484 seconds
49999995000000
Cython is faster than pure python by 268.0 times.
Cython is faster than pure python by 268.23 times.

参考文献

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4