Cython and ctypes
When Python is too slow, write C extensions with Cython (Python-like syntax), ctypes (call C libraries), or cffi.
When Python is too slow, write C extensions with Cython (Python-like syntax), ctypes (call C libraries), or cffi.
# 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
Profile first — 90% of programs spend 90% of time in 10% of code. Only optimise the hot path.