Python’s profiler, cProfile
, generates studies that present which features take up probably the most time in a given Python program. By default, Cython code doesn’t present up in these studies. Nevertheless, you’ll be able to allow profiling on Cython code by inserting a compiler directive on the prime of the .pyx
file with features you wish to embody within the profiling:
# cython: profile=True
You may also allow line-by-line tracing on the C code generated by Cython. Doing this imposes a variety of overhead, so it’s turned off by default. (Profiling typically imposes overhead, so remember to toggle it off for code that’s being shipped into manufacturing.)
Cython also can generate code studies that point out how a lot of a given .pyx
file is being transformed to C, and the way a lot of it stays Python code. The setup.py
file from our instance specified this with the annotate=True
assertion within the cythonize()
perform.
Delete the .c
recordsdata generated within the mission and re-run the setup.py
script to recompile every thing. Once you’re carried out, you must see an HTML file in the identical listing that shares the title of your .pyx
file—on this case, num.html
. Open the HTML file and also you’ll see the elements of your code which can be nonetheless depending on Python highlighted in yellow. You may click on on the yellow areas to see the underlying C code generated by Cython.

A Cython code annotation report. The yellow highlights point out elements of the code that also rely upon the Python runtime.
IDG
On this case, the def f
perform continues to be highlighted in yellow, regardless of having its variables explicitly typed. Why? As a result of it’s not annotated explicitly as a Cython perform. Cython assumes any perform not annotated with @cython.cfunc
is only a Python perform, and never convertible to pure C.
You may repair this by modifying the def f
declaration to learn:
@cython.cfunc
def f(x: cython.double) -> cython.double:
Save and recompile the file, and reload the report. It is best to now see the def f
perform is now not highlighted in yellow; it’s pure C.

The revised Cython perform, now pure C, generates no highlights.
IDG
Word that when you’ve got profiling enabled as described above, even “pure” C features will present some highlighting, as a result of they’ve been adorned with hint code that calls again into Python’s internals.
Additionally be aware that the division operation in line 12 can also be highlighted; it’s because Cython mechanically inserts assessments for division by zero, and raises a Python exception if that’s the case. You may disable this with the cdivision
compiler directive, or by the use of a decorator on the perform (@cython.cdivision(True)
).
Cython sources
Now that you’ve some thought of how Cython integrates with an current Python app, the following step is to place it to work in your personal functions, and to utilize different sources on the market: