プログラミング備忘録

初級プログラマ。python、DL勉強中

Cythonを使ってみた

Cythonを使ってみた

install

pipでinstall可能

pip install cython

pyxファイル

pyxファイルに実行したいソースを記載

def add(int a,int b):
    cdef float beta =0.2

    return beta+a+b

def mlt(int a,int b):
    cdef float alfa= 0.1

    return alfa*a*b

Compile

setup.pyを使用してコンパイル cythonチュートリアルのExtension引数を変更すれば、実行できた

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("cal", ["cal.pyx"])]

setup(
  name = 'Hello world app',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)

以下のコマンドを実行

python setup.py   build_ext --inplace

実行後、.cファイル .soファイル .oファイルが生成される

テストソース

import cal

A=8
B=5

print(cal.add(A,B))
print(cal.mlt(A,B))

結果

13.199999809265137
4.0