Cython "Hello World!"

In this notebook, we will simply verify that the IPython Cython magic commands work properly. If successful, you will be able to use Cython from within IPython and IPython notebooks.

The first step is to load the cythonmagic extension:


In [ ]:
%load_ext cythonmagic

If the above cell emits no error then a recent version of Cython is installed and IPython is able to find it.

This next cell will determine whether we can compile Cython code on the fly:


In [ ]:
%%cython
def add(int a, int b):
    return 3.1415926 * a + 2.718281828459045 * b
If the above cell emits no error, then you are able to compile and run Cython code inline. If you make a change to the above cell and re-execute, the %%cython magic function will detect the change, recompile, and import the new compiled code automatically. Let's define a pure-python version of the same function for comparison:

In [ ]:
def pyadd(a, b):
    return 3.1415926 * a + 2.718281828459045 * b

Lastly, let's compare the performance difference between the two:


In [ ]:
%timeit add(1, 2)
%timeit pyadd(1, 2)

I see about a factor of 2 speedup for the Cython version (127 ns vs. 256 ns).


In [ ]: