Programming

How to Make Python Actually Fast

Programmers tend to turn to Python for applications due to the convenience and it usually being programmer friendly – not exactly because it's a fast language or performs the best when you need performance. There is a plethora of third-party libraries while the language compensates heavily from…

How to Make Python Actually Fast

You picked Python because it's fast to write, not fast to run. That's the right trade until the profiler says the interpreter is the bottleneck. Then you have four real options — and they're not interchangeable.

Move the math to NumPy

Array math through the interpreter is work C does a hundred times faster. NumPy hands it to C libraries and stores data far tighter — roughly a quarter the memory of the equivalent Python list.

import numpy as np, time

data = list(range(1_000_000))
arr = np.array(data)

t=time.perf_counter(); sum(data); print(f"list: {time.perf_counter()-t:.3f}s")
t=time.perf_counter(); arr.sum(); print(f"numpy: {time.perf_counter()-t:.4f}s")
# typically ~10-30x faster on million-element sums

The catch: you rewrite in array syntax, and you begin with the right data structure or you rewrite twice.

Cython for the hot loops

Compile Python to C incrementally. Convert as-is and you get 15–50%; add type annotations and it compiles to pure C:

def total(double[:] values):
    cdef double s = 0
    cdef int i
    for i in range(len(values)):
        s += values[i]
    return s

The annotations are where the money is — orders of magnitude on CPU-bound loops. I/O-bound code gets nothing.

Multiprocessing beats the GIL

The Global Interpreter Lock keeps CPython threads on one core. multiprocessing runs interpreter instances across cores:

from multiprocessing import Pool
with Pool() as p:
    results = p.map(worker, items)

Process startup and data serialization are the tax — pay it on big batches, not tiny calls.

Change the interpreter

PyPy's JIT beats CPython several times over on long-running CPU-heavy code, drop-in. The catch is C-extension compatibility — measure before you commit.

When it breaks

Nothing helps until you've profiled. cProfile names where the time goes; guessing gets you a 3% improvement and a rewrite you didn't need.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.