Cython - How to compile

lun. 14 janvier 2019 by Martin Deudon

Cython is a tool that allows you to compile your code to C, resulting in a huge speed increase. All is needed is slight modification of the python code.

The Cython documentation : http://docs.cython.org/en/latest/

If you only need to compile some Cython file (.pyx extension), here is how it is done.

The Cython code (hello.pyx) is convert is a C code by the Cython compiler (hello.c), which is then compiled to create a dynamic library (hello.so)

To do all this create a python script, for example setup.py with the following content :

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

setup(
    ext_modules=cythonize("hello.pyx"),
    extra_compile_args=["-O3", "fopenmp"],
    extra_link_args=["fopenmp"],
    include_dirs=[numpy.get_include()]
)

Then, call this code from a terminal :

python setup.py

Requirements

  • The Cython module : Installing Cython
  • A C compiler - In Unix systems, the C compiler gcc should already be installed, on Windows you can install Visual Studio which includes a C compiler. See here to know which version is needed.