Sub topic 14
When to go native: Cython, Numba, and C extensions
This chapter assumes you can profile a program with cProfile and read tottime and cumulative time. It also assumes you know the earlier fixes: better algorithms, idiomatic Python, caching, NumPy vectorization, and process pools. You also need pip and, for the Cython example, a C compiler on your machine.
Native code is the last tool in the sequence, not the first. It can give large speedups on tight numeric loops. It also adds build steps, platform issues, and a second language to maintain. The goal here is to decide when that cost is justified and to try the two lowest-friction options.
What "native" means and why it is faster
CPython runs bytecode in an interpreter. Each operation such as total += i * i involves type checks, object allocation for the intermediate integers, and reference counting. A compiled loop over machine integers avoids almost all of this.
Native approaches remove that overhead in one of three ways:
- Compile your Python-like code: Numba compiles functions at run time. Cython compiles
.pyxfiles ahead of time. - Call existing compiled code: bindings such as
ctypes,cffi, and pybind11 let Python call a C or C++ library. - Write a C extension: you write C against the CPython API, or use a helper such as Cython or pybind11 to generate the glue.
The speedup comes from the loop body, not from the call. Calling a native function with tiny work inside it saves nothing, because the call itself crosses the Python/native boundary and costs time.
Before you go native: a checklist
Reach for native code only when all of these hold:
- A profile shows one function, or a few, that account for most of the runtime.
- The hot code is a loop over numbers or arrays that cannot be written as NumPy operations. Typical cases are loops where each step depends on the previous one, or algorithms with data-dependent branching.
- You already fixed the algorithm and data structure. A compiled O(n²) loop still loses to an interpreted O(n log n) one once n is large.
- The gain needed is larger than what vectorization, caching, or a process pool can deliver.
If the time is spent waiting on a network or disk, native code does not help. If the time is in an existing NumPy or pandas call, you are already running native code.
Numba: compile a function with a decorator
Numba is a just-in-time (JIT) compiler. The first call to a decorated function compiles it to machine code for the argument types it sees. Later calls reuse that code. It works best on functions that use numbers, NumPy arrays, and plain loops.
Install it with pip install numba numpy. Then run this:
import time
import numpy as np
from numba import njit
@njit(cache=True)
def sum_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)
start = time.perf_counter()
sum_squares(values) # first call includes compilation
first = time.perf_counter() - start
start = time.perf_counter()
result = sum_squares(values)
second = time.perf_counter() - start
print(result)
print(f"first call: {first:.4f}s")
print(f"second call: {second:.6f}s")The first call is slow because it compiles. The second call shows the real speed. This is why timing a Numba function once gives a misleading result. Always call it once before you measure, as the example does.
Points to know:
@njitis shorthand for@jit(nopython=True). It raises an error if Numba cannot compile the whole function without falling back to the interpreter. This is what you want, because a silent fallback gives no speedup.cache=Truestores the compiled code on disk so later runs skip most of the compile time.- Numba supports a subset of Python and NumPy. Arbitrary objects, most third-party libraries, and many dynamic features are not supported inside a compiled function.
- Integer overflow behaves like C, not Python. Python integers grow without limit, but a compiled
int64wraps around. Check that your sums fit in 64 bits.
Cython: add types and compile ahead of time
Cython translates .pyx files to C, which a compiler then turns into an importable module. Plain Python is valid Cython, but it gets faster only when you declare C types for the variables in the hot loop.
Create sumsq.pyx:
def sum_squares(long long n):
cdef long long i
cdef long long total = 0
for i in range(n):
total += i * i
return totalCreate setup.py next to it:
from setuptools import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("sumsq.pyx"))Build and test it:
pip install cython setuptools
python setup.py build_ext --inplace
python -c "import sumsq; print(sumsq.sum_squares(1_000_000))"The cdef lines declare C variables, so the loop runs on machine integers with no Python objects. If you delete the cdef lines, the code still works but runs at close to normal Python speed. Cython can produce an annotated HTML report with cython -a sumsq.pyx. It colors lines by how much Python machinery they still use, which tells you where to add types.
Cython is more work than Numba, but it has advantages:
- It produces a normal compiled module, so users do not need a JIT at run time.
- It can call C libraries directly and handle arbitrary Python objects.
- It gives finer control over memory, for example with typed memoryviews over NumPy arrays.
Wrapping existing native code
Sometimes the fast code already exists as a C, C++, or Rust library. You do not need to rewrite it, only to call it.
| Tool | Best for | Cost |
|---|---|---|
| `ctypes` | Calling a shared library function from the standard library, no build step | You declare argument and return types by hand. A wrong declaration can crash the interpreter. |
| `cffi` | Cleaner bindings to C, with a build mode that checks against the headers | An extra dependency and some setup |
| pybind11 | Exposing C++ classes and functions to Python | A C++ build in your project |
| Hand-written CPython C extension | Maximum control, or code that must ship with no dependencies | The most code, manual reference counting, and the highest risk of crashes |
For most projects, avoid the hand-written extension. Cython or pybind11 generate most of that glue and make fewer memory-management mistakes.
Comparing the options
| Aspect | Numba | Cython | C extension or binding |
|---|---|---|---|
| Setup effort | `pip install` and a decorator | Compiler, `.pyx` file, build step | Compiler, build system, C or C++ code |
| Startup cost | Compile on first call, unless cached | None at run time | None at run time |
| Language | Subset of Python | Python plus C type declarations | C or C++ |
| Distribution | Users need Numba and its LLVM dependency | Ship wheels per platform | Ship wheels per platform |
| Debugging | Error messages can be hard to read | Generated C can be hard to read | Native debuggers, crash risk |
| Typical use | Numeric loops over arrays | Typed loops, C library calls, mixed objects | Reusing existing libraries |
Failure modes to watch for
- Measuring compile time. Warm up Numba functions before timing, and report the steady-state number. Also record the first-call cost if your program runs only once, because for short scripts compile time can exceed the savings.
- Boundary overhead. Calling a compiled function a million times with small inputs can be slower than one call that loops internally. Move the loop into the compiled code.
- Conversions. Passing Python lists into Numba forces conversion each call. Pass NumPy arrays.
- Different results. Fixed-width integers overflow, and floating-point operations can be reordered by the compiler. Compare outputs against the pure Python version on test inputs.
- Packaging. Cython and C extensions need a compiler at build time and platform-specific wheels. This is a real maintenance cost for libraries.
Confirm the gain
After any native change, run the same timing or profile that found the hot spot. Check three things:
- The function is faster in steady state, using
time.perf_counterortimeiton warmed-up code. - The whole program is faster. Amdahl's law applies: if the function was 30% of runtime, even an infinite speedup saves at most 30%.
- The results match the pure Python version.
The next step is to put that comparison into a benchmark that fails when the speedup disappears.
Exercise
Your profile shows a function that loops over a 5-million-element NumPy array, where each step uses a value computed in the previous step, so NumPy operations cannot express it. You decide to try Numba. You time one call to the decorated function and find it is slower than the pure Python version. What are two likely causes, and how do you check each?
Show answer
First, the call includes compile time. Call the function once to warm it up, then time later calls (or use cache=True and run again). Second, the function may not compile in nopython mode, or it may receive a Python list that must be converted on every call. Use @njit so that a failed compile raises an error, and pass a NumPy array. If the steady-state call is still no faster, check that the loop is the real hot spot with cProfile.
Exercise
A function accounts for 40% of a program's runtime. You rewrite it in Cython and it runs 50 times faster. About how much faster is the whole program, and what does this tell you about where to look next?
Show answer
The function's share falls from 40% to 0.8% of the original time, so the total is 0.6 + 0.008 = 0.608 of the original. That is about 1.64 times faster. The remaining 60% now dominates, so profile again and look at the rest of the program before doing more native work on this function.