のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

Cythonを使って、Pythonを高速化してみよう①:インストール

Sponsored Links

皆さんこんにちは
お元気ですか。私は元気です。

最近、このブログの色がPythonに傾きつつあるようなないような。
今日はCythonをご紹介したいと思います。

Cythonとは?

C言語によるPythonの拡張モジュールの作成の労力を軽減することを目的として開発されたプログラミング言語である(by Wikipedia)

特徴として

  • CやC++の関数を使える
  • C++やCで使える型を使うことで高速化が図れる
  • 大きいデータとかで、Numpyなどを効果的に扱うことができる。

が挙げられ、型をつけるだけで、なんと100倍速を実現できるとかできないとか。

インストール

sudo pip install cython

公式にあるExampleの実行

フィボナッチ数列の計算です。

fib.pyx

def fib(n):
    """Print the Fibonacci series up to n."""
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a + b

setup.py

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("fib.pyx"),
)

実行

$ python setup.py build_ext --inplace
running build
running build_ext
skipping 'fib.c' Cython extension (up-to-date)
building 'fib.pyx' extension
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c fib.c -o build/temp.macosx-10.9-intel-2.7/fib.o
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1

よくわからないargumentが走っていることでエラーが出ています。
以下のコマンドを打つと回避することができます。

export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments

実行ですが、以下の感じになります。

$ python
>>> import fib
>>> fib.fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597