Cython and C Extensions
A way to speed up performance-critical Python code by compiling it (or a variant of it with type annotations) down to C, removing the interpreter overhead that makes plain Python loops slow.
Python's flexibility comes at a cost: every loop iteration re-checks variable types and dispatches through the interpreter, which makes tight numerical loops far slower than the equivalent C code. Cython addresses this by letting you write Python-like code, optionally annotated with static C types, that gets compiled ahead of time into a genuine C extension module — a .so or .pyd file Python can import like any other module, but that runs at close to native C speed for the annotated parts.
The typical workflow: take a slow Python function, add cdef type declarations to its hottest variables and loop counters, and let Cython's compiler generate C code that skips the interpreter's per-operation type checks. Unlike Numba's just-in-time approach, Cython compiles ahead of time and also makes it straightforward to call existing C or C++ libraries directly, which matters when a firm already has a mature C++ pricing library it wants Python researchers to call without a rewrite.
Worked example. A pure-Python loop summing squares of a million floats might take tens of milliseconds; the same loop rewritten in Cython with cdef double type declarations on the loop variable and accumulator can run 20-50x faster, because the compiled version does no per-iteration type dispatch at all.
Cython compiles Python-like, optionally type-annotated code into a real C extension, removing interpreter overhead for hot loops and making it natural to call existing C/C++ libraries directly — the main alternative to Numba's just-in-time compilation for speeding up Python.
Related concepts
Practice in interviews
Further reading
- Cython documentation, cython.org