Cython: Compiling Python to C with Static Types

This article explains how Cython compiles Python code into C extension modules, why static types produce the largest gains, and why some benchmarks measure the compiler instead of the loop.

Close view of a green snake with white markings, its head resting on its own coils beside a fern leaf
Photo by David Trinks on Unsplash

The interpreter of CPython executes every operation of a Python function through generic machinery: each integer is an object on the heap, and each addition is dispatched at run time according to the types of its operands. The present article examines Cython, a language that extends Python with C type declarations and translates a module into C, which a C compiler then turns into an extension module that Python imports like any other. It measures a pure Python loop and its idiomatic alternatives, follows the steps from a .pyx file to a compiled module, explains why static types produce the largest gains, and analyses a frequently quoted benchmark whose result reveals more about the C compiler than about the loop. Removing the interpreter from the one function that consumes most of the time, while the rest of the program remains in Python, is the secret weapon of Cython.

Measuring the Pure Python Baseline

A loop that adds the integers from zero to n is the usual example of CPU-bound code, because it performs no input or output and spends all its time in the interpreter. Before any compilation, the baseline must be measured, and the alternatives that Python already offers must be considered.

import timeit

def sum_a_lot(n):
    total = 0
    for i in range(n):
        total += i
    return total

n = 10_000_000
loop = timeit.timeit(lambda: sum_a_lot(n), number=1)
builtin = timeit.timeit(lambda: sum(range(n)), number=1)
formula = timeit.timeit(lambda: n * (n - 1) // 2, number=1)

print(sum_a_lot(n) == sum(range(n)) == n * (n - 1) // 2)  # Output: True
print(builtin < loop)    # Output: True
print(formula < builtin)  # Output: True

On the machine used for this article, with CPython 3.12, the explicit loop took about 0.23 seconds for ten million iterations, whereas the built-in sum over a range took about 0.08 seconds, nearly three times less, because its loop runs in C. The arithmetic formula takes microseconds regardless of n. The example therefore shows the first rule of optimization: a better algorithm or a built-in function often removes the need to compile anything, and Cython becomes relevant only when the computation has no such shortcut.

From a .pyx File to an Extension Module

Cython accepts almost any Python code, so the first step consists of copying the slow function, unchanged, into a file with the extension .pyx.

# fast_code.pyx
def sum_a_lot(n):
    total = 0
    for i in range(n):
        total += i
    return total

The file is then translated into C and compiled. The documentation of Cython describes a setup.py file that calls cythonize as the normal way to build a module, and it also offers a shorter command that builds the extension in place:

pip install cython
cythonize -i fast_code.pyx

The command produces a file whose name encodes the interpreter and the platform, such as fast_code.cp314-win_amd64.pyd on Windows or fast_code.cpython-314-x86_64-linux-gnu.so on Linux, and import fast_code loads it. The build requires a C compiler compatible with the Python installation, and the resulting binary works only for that version of Python and that platform; for that reason, the listings in Cython syntax are presented as source files to be built, not as scripts that the interpreter runs directly. Compiling the untyped function removes the overhead of interpreting each bytecode instruction, but the variables remain Python objects and every addition still goes through the generic protocol of integers, so the gain is typically modest.

Static Types: Where the Speed Comes From

A speedrunner who already knows the layout of every level does not stop to inspect each room, because the route was decided before the run began. Static types give the C compiler the same advance knowledge: once a variable is declared as a C integer, the addition becomes a single machine instruction on a value held in a register, with no object, no dispatch and no memory allocation. The analogy, however, stops at this point, because a speedrun may skip parts of the game, whereas the compiled function must still compute the same result as the Python version for every input, an obligation that a C type of insufficient width silently breaks.

# fast_code.pyx
cpdef long long sum_a_lot(long long n):
    cdef long long total = 0
    cdef long long i
    for i in range(n):
        total += i
    return total

The keyword cdef declares C variables, and cpdef creates a function that Python code can call and that other Cython code calls through the faster C calling convention. The type long long is deliberate: the C type long has 64 bits on Linux and macOS but only 32 bits on Windows, the same difference that affects c_long in the article devoted to ctypes. Cython itself avoids translating an int annotation into a C integer by default, since the behaviour of C integers differs from that of Python integers with respect to overflow and division. The same declarations can also be written in pure Python mode, with annotations such as cython.longlong and the decorator @cython.ccall, so that the file remains valid Python.

Pitfalls of Cython

Compiled code is faster only when the measurement and the types are correct, and both fail in ways that are not obvious. Six pitfalls are distinguished, which are the following:

  1. Benchmarks that the compiler removes. A typed loop over 100 million integers reported as taking 0.0001 seconds would imply a trillion additions per second, which no processor core performs; the C compiler has replaced the loop by a formula or discarded it, so the figure measures the optimizer, not the loop.
  2. Silent overflow. C integers wrap around or produce undefined behaviour when a result exceeds their width, whereas Python integers grow without limit.
  3. Compiling without types. An untyped .pyx file still manipulates Python objects, and its gain is small compared with that of typed code.
  4. Python objects inside typed code. Calls to Python functions, lists and dictionaries keep their interpreter costs; the command cython -a produces an annotated report that highlights the lines that still interact with Python.
  5. Build and distribution. Every platform and every version of Python needs its own compiled binary, which complicates installation compared with a pure Python package.
  6. Optimizing the wrong code. Code that waits for the network, the disk or a database gains nothing from compilation, and only a profiler shows which function deserves it, as explained in the article devoted to profiling.

The second pitfall can be reproduced without a compiler, by computing in Python the value that the typed function must return and the value that a 32-bit integer would hold.

import ctypes

n = 100_000_000
total = n * (n - 1) // 2
print(total)                   # Output: 4999999950000000
print(total > 2**31 - 1)       # Output: True
print(total > 2**63 - 1)       # Output: False
print(ctypes.c_int32(total).value)  # Output: 887459712

The correct sum exceeds the largest 32-bit signed integer but fits in 64 bits, so a version of the function declared with long returns the correct value on Linux and a wrong one on Windows, where the truncated result would typically be 887459712, with no error in either case. The type long long, which has at least 64 bits on every platform, avoids the problem for this input, and an input large enough to exceed 64 bits would require a check or a Python integer.

Choosing an Optimization Strategy

Consequently, compilation is one option among several, and the cheaper ones should be exhausted first, as the following table summarizes.

Situation Recommended approach
The slow function has an algorithmic shortcut A better algorithm or a built-in, such as sum
Numerical operations over whole arrays NumPy, whose loops already run in C
A CPU-bound loop with no shortcut, in a known bottleneck Cython with static C types
An existing C library must be called ctypes for a few calls; Cython for an extensive wrapper
The program waits for input and output Threads or asyncio, not compilation
The bottleneck is unknown A profiler before any change

Conclusion

It is concluded that Cython speeds up Python code by translating it into C, and that the largest gains come from static type declarations that let the C compiler operate on machine values instead of Python objects, provided that those types are wide enough for every input. This magic has a cost in build complexity and in the care that C integer semantics demand, and its benchmarks must be read critically, since a result that seems too fast usually measures the work that the compiler removed. The same compiled modules can also be written by hand in C, against the C API of CPython, an approach that is developed in a future article of this series.