Sub topic 14
When to go native: Cython, Numba, and C extensions
This chapter assumes you can read a cProfile report, have already fixed algorithm and data-structure problems, and have tried NumPy vectorization. Native code comes last because it is the most expensive fix to maintain.
What "native" means
CPython runs bytecode through an interpreter, and every operation on an int goes through object checks and reference counting. Native code is compiled to machine instructions and works on raw machine integers and floats. A tight numeric loop can run tens to hundreds of times faster once it is compiled.
Native code pays off only when all of these are true:
- The profiler shows one small function dominating the runtime.
- That function is a loop over numbers or arrays that vectorization cannot express cleanly.
- The algorithm is already sound.
If most of the time goes to I/O, database calls, or a slow algorithm, compiling the code will not help.
The three main options
| Option | How you use it | Best for | Main cost |
|---|---|---|---|
| Numba | Add a decorator to a Python function | Numeric loops over NumPy arrays | Supports only a subset of Python and NumPy |
| Cython | Add type annotations, then compile ahead of time | Hot functions and wrapping C libraries | Needs a build step and a compiler |
| C extension | Write C against the Python C API | Reusing existing C code, maximum control | Manual memory and reference management |
Numba: the smallest change
Numba compiles a function to machine code the first time you call it. Install it with pip install numba.
import numpy as np
from numba import njit
@njit
def sum_of_squares(values):
total = 0
for i in range(values.shape[0]):
total += values[i] * values[i]
return total
values = np.arange(1_000_000, dtype=np.int64)
sum_of_squares(values) # first call compiles, so do not time this one
print(sum_of_squares(values))@njit means "no Python mode". If Numba cannot compile something inside the function, it raises an error instead of silently running slowly. The first call includes compile time. When you benchmark, call the function once to warm it up, then time later calls.
Cython: typed code compiled ahead of time
Cython turns Python-like code into C, which you then compile. Its pure-Python mode keeps the file valid Python. Save this as sum_squares.py:
import cython
def sum_of_squares(n: cython.int) -> cython.longlong:
total: cython.longlong = 0
i: cython.int
for i in range(n):
total += i * i
return totalBuild it in place with cythonize -i sum_squares.py, then import sum_squares as usual. Without compiling, the file still runs as ordinary Python, just slowly. The speedup comes from the C types, so untyped Cython code gains little.
C extensions
A C extension is a shared library that implements the CPython C API. You manage reference counts and error handling yourself, and a mistake can crash the interpreter. Write one when you must wrap an existing C library or need control that the other tools do not give you. Check whether ctypes, cffi, or a binding generator such as pybind11 covers your case first.
Deciding
Exercise
A profile shows 90% of runtime in a function that loops over a NumPy array and applies a branching calculation that vectorization cannot express. Which tool do you try first, and why must you avoid timing its first call?
Show answer
Try Numba first, because adding @njit needs the smallest code change. Its first call includes compilation time, so call the function once to warm it up and time only later calls.