ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

【Python】Cython試してみた

スポンサードリンク

Jupyterではマジックコマンド?を書けばすぐ実行できるけど、コマンドラインから実行するやりかたがわからなかったのでメモ。

  • setup.py
# -*- coding:utf-8 -*-

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Compiler import Options
import numpy

Options.annotate = True

ext_modules = [Extension('example_cython', ['example.py'], language='c++')]

setup(cmdclass={'build_ext': build_ext}, ext_modules=ext_modules, include_dirs = [numpy.get_include()])

これで実行する。

$ python setup.py build_ext --inplace

いろいろできている。

$ ls -lt
-rw-r--r--  1 user staff       141  5 22 18:42 example.py
-rwxr-xr-x  1 user staff    159116  5 22 18:39 example_cython.cpython-36m-darwin.so
drwxr-xr-x  3 user staff       102  5 22 18:39 build
-rw-r--r--  1 user staff    376329  5 22 18:39 example.html
-rw-r--r--  1 user staff    414963  5 22 18:39 example.cpp
-rw-r--r--  1 user staff       403  5 22 18:39 setup.py

soファイルをリネームする

$ mv example.cpython-36m-darwin.so example_cython

pythonで読み込んでみる

$ python
>>> import example_cython

これでおk.あとは普通にpythonから使えるようになる(はず)

ちなみに、速度はそんなにかわりませんでした・・・なぜ?