Cython

Introduction

Cython is a compiler which compiles Python-like code files to C code. The resulting functions can then be imported into other Python scripts.

This method can be used to increase the execution speed of a Python script, particularly if the script uses for-loops.

The Python-like *.pyx script which provides the function must have have static C data types in order for the main Python script to gain full speed performance.

Installation

Cython can be installed on a Ubuntu system using the “Ubuntu Software Center.”

It is also bundled with the Enthought Python Distribution [EPD] and with Sage Notebook.

Steps

Using Cython consists of these steps:

1. Write a .pyx source file for the function

2. Write a setup.py file using the disutils function

3. Compile the source code in command-line mode using: python setup.py build_ext –inplace

4. Import the function into the main Python script and then run it
There are a few alternative compiler methods, but disutils is the most reliable from the author’s experience.

Examples

Cython: Runge-Kutta

Cython: Fourier transform

Tom Irvine

Leave a comment