Cython tutorial: How to speed up Python

How to use Cython and its Python-to-C compiler to give your Python applications a rocket boost

1 2 Page 2
Page 2 of 2

In this case, the cdef f function is still highlighted in yellow, despite being a cdef function and having its variable explicitly typed. Why? Because the return value of the function isn’t typed. Cython assumes that the function will return a Python object, not a C double, so has generated Python API code to handle that.

You can fix this by editing the cdef f declaration to read:

cdef double f(double x):

Save and recompile the file, and reload the report. You should now see the cdef f function is no longer highlighted in yellow; it’s pure C.

cython report 02 IDG

The revised function, now pure C, generates no highlights.

Note that if you have profiling enabled as described above, even “pure” C functions will show some highlighting, because they have been decorated with trace code that calls back into Python’s internals.

Also note that the division operation in line 8 is also highlighted; this is because Cython automatically inserts tests for division by zero, and raises a Python exception if that’s the case. You can disable this with the cdivision compiler directive, or by way of a decorator on the function (@cython.cdivision(True)).

Cython resources

Now that you have some idea of how Cython integrates with an existing Python app, the next step is to put it to work in your own applications, and to make use of other resources out there:

  • The official Cython documentation is your best next step. It contains many tutorials that cover separate aspects of Cython, such as working with Python’s native array datatype.
  • The Cython code repository on GitHub also has a wiki with useful tips.
  • If you have a question that isn’t covered by the docs, ask in the official cython-users mailing list. Cython’s core developers read the list and provide highly technical, detailed answers.
  • You’ll find a treasure trove of Cython questions and answers on Stack Overflow. If you have a specific technical question about using Cython, odds are someone has answered it.
  • Cython by Kurt Smith is a book-length exploration of working with Cython that covers various features of Cython and details many usage scenarios. Note that the book only refers to the feature sets for Cython up to version 0.21, although most of the material remains valid and applicable.
  • Another useful book is High Performance Python by Micha Gorelick and Ian Ozsvald. It isn’t as comprehensive as Smith’s book, but offers a broader perspective on Cython as one among several technologies that can be used to improve the performance of Python applications.

Read more about Python

Copyright © 2020 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2