SyntaxStudy
Sign Up
Python Python Performance with C Extensions
Python Advanced 5 min read

Python Performance with C Extensions

Cython and ctypes

When Python is too slow, write C extensions with Cython (Python-like syntax), ctypes (call C libraries), or cffi.

Example
# Cython: save as compute.pyx
def fast_sum(list[double] data) -> double:
    cdef double total = 0
    cdef int i
    for i in range(len(data)):
        total += data[i]
    return total
# compile: python setup.py build_ext --inplace

# ctypes: call existing C library
from ctypes import CDLL, c_double
libm = CDLL("libm.so.6")
libm.sqrt.restype = c_double
print(libm.sqrt(c_double(16.0)))  # 4.0
Pro Tip

Profile first — 90% of programs spend 90% of time in 10% of code. Only optimise the hot path.