Sunday, July 24, 2011

Using Cython

The easiest way to convert old python code for use with cython is to rename your python file into something with the extension .pyx. This .pyx file can then be compiled with the (for distutils)script.

Here is an example which also shows how to include the math libray (-lm for gcc)

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

ext_modules = [Extension("BvL_cython",["BvL_cython.pyx"],\

    name= 'BvL model class',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules

The reason that I was interested in Cython was the long calculation times I encountered while doing a multi-variable optimization with a function evaluation that involved solving a differential equation with scipy.integrate.odeint. By simply replacing the class that contained the differential equation with a Cython version the calculation time dropped by a factor 5. Not bad for half a Sunday afternoons work.


  1. I am trying to do the exact same thing: use Cython to reduce the time for optimizations that involve scipy.integrate.odeint. Can you post a full example or would you be willing to email me your files? I haev a grad student working on this project and he is having trouble converting the pure python version to cython.

  2. In the weekend I will try to post a full example (I do not have time right now and I have to edit it a bit)

  3. Done. See the post of 10 december 2011.