Lesson 7 of 9 · 25m
Cython: Keep Python's Shape, Drop the Hot Loop into C
When a measured hot loop cannot vectorize, Cython can compile typed Python-like code into C. The wins come from types, memoryviews, and knowing what still crosses back into Python.
Cython earns its place in a narrow but important situation: the hot loop is real Python arithmetic or object manipulation, NumPy cannot express it cleanly, and rewriting the whole service in another language is not justified. Done well, Cython preserves most of the code's shape while removing interpreter dispatch from the critical path. Done badly, it adds build and release complexity for a 3% improvement — which is why it belongs after profiling, not before.
Start with a small, measured kernel
Suppose profiling points here:
def score_events(events):
total = 0.0
for event in events:
total += event.value * event.weight
return totalTyping variables alone is often disappointing when the loop still performs Python attribute access on object values. Larger wins come when the data itself can be numeric arrays or typed structs. For numeric buffers, typed memoryviews are the idiomatic tool:
# kernels.pyx
def weighted_sum(double[:] values, double[:] weights):
cdef Py_ssize_t i
cdef double total = 0.0
for i in range(values.shape[0]):
total += values[i] * weights[i]
return totalNow the loop indexes contiguous C-level memory rather than boxing and unboxing Python floats.
Build it like a normal package
# setup.py
from setuptools import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize(["kernels.pyx"], language_level="3"))python -m pip install cython setuptools numpy
python setup.py build_ext --inplace
python -c "import numpy as np, kernels; print(kernels.weighted_sum(np.ones(4), np.full(4, 0.5)))"For real projects, move this into pyproject.toml and a proper build backend. Do not commit generated C files casually unless your release process intentionally vendors them.
Disable checks only after correctness is proven
Cython inserts safety checks for negative indexing and bounds:
# cython: boundscheck=False, wraparound=FalseThose directives can speed tight loops, but they turn indexing mistakes into memory corruption rather than exceptions. Earn them with tests and fuzzed edge cases. A segfault in production is not a performance strategy.
Field notes
- Type the data, not just variable names.
objecteverywhere means Python overhead everywhere. - Keep the extension boundary wide: pass arrays or batches, not millions of tiny calls.
with nogil:only helps if the enclosed code avoids Python objects and does not call back into Python APIs.- Cython is easiest to justify for stable kernels. Rapidly changing business logic often belongs back in maintainable Python.
Was this lesson helpful?