O'Reilly logo

Learning Cython Programming by Philip Herron

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Compiling pure Python code

Another use for Cython is to compile Python code; for example, if we go back to the primes example, we can do the following:

philips-macbook:primes redbrain$ cython pyprimes.py –embed
philips-macbook:primes redbrain$ gcc -g -O2 pyprimes.c -o pyprimes `python-config --includes –libs`

Then, we can compare the three different versions of the same program: the fully Cythoned version, the pure Python version, and the Cython-compiled pure Python version:

philips-macbook:primes redbrain$ time ./primes
real    0m0.050s
user    0m0.035s
sys     0m0.013s

The fully Cython version runs the fastest!

philips-macbook:primes redbrain$ time ./pyprimes
real    0m0.139s
user    0m0.122s
sys     0m0.013s

The compiled pure Python version runs considerably faster ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required