Skip to content
BIASED

Writing fast Python

Speed code up in the order that pays — measure and bound the gain with Amdahl's law, choose the data structure, trim interpreter overhead in the hot loop, hand the work to built-ins and NumPy, and compile only one function.

Optimizing by intuition

The topic How CPython runs code showed what each line of Python costs: a dispatch for every bytecode instruction, a frame for every call, a heap object for every intermediate number, a reference-count update for every stored reference. Specialization makes some of these cheap, and the JIT in 3.14 is still experimental. This topic turns those costs into practice: how to make a program faster, and in what order.

The usual way is to look at the code, find the line that looks expensive and rewrite it in a cleverer form. Here is why that fails. Take a program like the vocabulary builder from the topic Debugging and profiling: build 100,000 random words, normalize them, collect the distinct ones.

import random
 
def make_text(n_words, vocab, seed=1):
    rng = random.Random(seed)
    return " ".join(f"w{rng.randrange(vocab)}" for _ in range(n_words))
 
def tokenize(text):
    return [w.strip(".,").lower() for w in text.split()]
 
def unique_words(words):
    seen = []
    for w in words:
        if w not in seen:
            seen.append(w)
    return seen

tokenize looks wasteful: two string methods and a new string per word. It is the obvious target. Now time each step with perf_counter. One run with Python 3.14.7 on an Apple M1 laptop gave:

Step Time
make_text 0.0225 s
tokenize 0.0062 s
unique_words 1.4576 s

Your numbers will differ. Even on this laptop a later run, with other programs busy, took 1.7 s for the last step. Only comparisons within one run mean anything. And the comparison here is brutal: making tokenize infinitely fast would barely register.

Speed comes from three places, in decreasing order of payoff:

  1. Do less work: a better algorithm or data structure.
  2. Do the remaining work in fewer interpreter steps: fewer calls in the hot loop, built-ins, comprehensions.
  3. Take the loop out of the interpreter: NumPy, or compiled code.

And before any of them: measure, so you know which part to work on.

Amdahl's law

How much can speeding up one part gain? Split the run time TT into the part we speed up, pTpT, and the rest, (1−p)T(1-p)T. Here pp is the part's share of the time. Speeding the part up by a factor ss leaves the rest unchanged:

Tnew=(1−p) T+p Ts.T_{\text{new}} = (1-p)\,T + \frac{p\,T}{s}.

The speed-up of the whole program is the ratio of the two times:

S=TTnew=1(1−p)+p/s.S = \frac{T}{T_{\text{new}}} = \frac{1}{(1-p) + p/s}.

As ss grows without bound, p/sp/s goes to zero, so

S≤11−p.S \le \frac{1}{1-p}.

This is Amdahl's law (Amdahl, 1967). It says two things.

  • A part that takes 2 % of the time can never save more than 2 %, however clever the rewrite.
  • Even a part that takes 98 % caps the speed-up at 50×. The other 2 % stays.

So the order of work is: profile with cProfile to find the part that dominates, read off pp, and compute the bound before writing any code. For the word count, unique_words takes p=1.4576/1.4863=0.981p = 1.4576 / 1.4863 = 0.981 of the run, so no change to it can make the program more than about 52 times faster. For tokenize, the bound is a rounding error.

The right data structure

Why is unique_words slow? Almost all of its time goes into one expression, w not in seen, with seen a list. in on a list is a linear scan: compare w with each element until one matches or the list ends. On a set it is a hash lookup, as in the topic Dictionaries and sets: compute hash(w), jump to a slot, compare with the few entries there.

Here is what that difference costs. timeit times a test for an absent element, the worst case for a list:

import timeit
 
for n in [1_000, 10_000, 100_000]:
    data = list(range(n))
    s = set(data)
    t_list = min(timeit.repeat("-1 in data", globals=globals(), number=1000, repeat=5))
    t_set = min(timeit.repeat("-1 in s", globals=globals(), number=1000, repeat=5))
    # timeit returns seconds for 1000 tests: * 1e6 gives ns per test
    print(f"n = {n:>7,}   list {t_list * 1e6:9,.0f} ns   set {t_set * 1e6:4.0f} ns")
n =   1,000   list     7,680 ns   set   11 ns
n =  10,000   list    75,904 ns   set   11 ns
n = 100,000   list   800,130 ns   set   11 ns

Ten times more elements, ten times the time for the list: about 7.7 ns per element on this laptop. The set stays at 11 ns whatever the size.

The word-count loop does one test per word. With mm words and a list that grows to kk distinct entries, each test scans up to kk entries, so the loop does up to m⋅km \cdot k comparisons. With a set, it does mm constant-time lookups. Changing seen = [] to seen = set() and append to add brought unique_words from 1.4576 s to 0.0034 s, so s≈429s \approx 429. Amdahl's law then predicts

S=10.0192+0.981/429≈46.S = \frac{1}{0.0192 + 0.981/429} \approx 46.

The whole program, measured, went from 1.4862 s to 0.0327 s: S≈45S \approx 45. The law works, and no trick in the rest of this topic comes near a factor of 400.

The same reasoning applies to every structure:

Slow pattern Cost Replacement Cost
x in some_list in a loop O(n)O(n) per test a set or dict built once O(1)O(1) on average
lst.pop(0), lst.insert(0, x) O(n)O(n) collections.deque O(1)O(1) at both ends
lst.count(x) for each item O(n)O(n) per item collections.Counter O(1)O(1) per item
linear search in a sorted list O(n)O(n) bisect O(log⁡n)O(\log n)
s += piece to build a string may copy s each time "".join(pieces) O(total length)O(\text{total length})
recomputing a pure function every call functools.cache a dict lookup after the first

Interpreter costs on 3.14

Once the algorithm is right, what remains is executing bytecode. To see what each construct costs, time loops of a million iterations that do almost nothing, so the difference between two loops is the cost of the one thing they change. For example, a function call:

def times3(i):
    return i * 3
 
def inline(n):
    t = 0
    for i in range(n):
        t += i * 3
    return t
 
def called(n):
    t = 0
    for i in range(n):
        t += times3(i)
    return t

Each variant ran with n=106n = 10^6, best of 5 runs, on the same laptop:

Loop body ns per iteration
t += i * SCALE, SCALE a module global 34.9
t += i * scale, scale a local copy 33.7
t += i * self.scale 35.7
t += i * 3 (inline) 33.7
t += times3(i) (called) 46.5
out.append(i * 3) in a for loop 32.0
[i * 3 for i in range(n)] 29.4

What the table says about CPython 3.14:

  • Globals and attributes are cheap once specialized. A global costs about 1 ns more than a local, an attribute about 2 ns. Before the specializing interpreter of 3.11 these lookups were far less optimized, and the classic advice to copy them into locals before a hot loop gained much more than it does now.
  • A Python call is the expensive step. A new frame, the argument copied in, a return.
  • Comprehensions beat append loops modestly, because they skip looking up and calling out.append on each pass. Write them because they are clearer.
  • Nothing goes below about 30 ns. Even t += i * 3 dispatches several instructions, allocates an integer and updates reference counts. That floor is the price of the interpreter.

The common mistake is to apply these tricks everywhere: alias every method, inline every function. They cost readability for a few percent, and pay only in the loop the profiler named.

Built-ins against loops

The floor of 30 ns is per iteration in Python. A built-in written in C also loops, but as machine code, with no bytecode between elements. So when a built-in does the whole loop (sum, min, max, sorted, any, all, str.join, math.fsum, math.sumprod), call it instead of writing the loop.

There is a catch. Take the sum of squares of a million floats in a list xs, four ways, best of 5 on the same laptop:

Code ns per element
for x in xs: t += x * x 19.84
sum(x * x for x in xs) 21.37
sum([x * x for x in xs]) 27.80
math.sumprod(xs, xs) 5.54

sum runs in C, yet the generator version is no faster than the plain loop, and the list version is slower still: it first builds a list of a million floats, then sums it. Only math.sumprod (new in 3.12) is clearly faster, about 3.6 times. The rule: a built-in helps when the per-element work moves into C, not merely the loop around it.

Vectorization with NumPy: a preview

math.sumprod still reads each element from a Python float, a 24-byte heap object that the list points to. NumPy stores the same million numbers as one contiguous block of 8-byte doubles, and its operations run C loops directly over that block. Writing a computation as operations on whole arrays, so the loop over elements runs in compiled code, is called vectorization.

import math
import numpy as np
 
arr = np.random.default_rng(0).random(1_000_000)
xs = arr.tolist()
 
def loop(values):
    t = 0.0
    for x in values:
        t += x * x
    return t
 
print(loop(xs))
print(math.sumprod(xs, xs))
print(arr @ arr, (arr * arr).sum())
333560.6157428297
333560.61574281874
333560.6157428189 333560.61574281874

The four results agree in their first 13 significant digits. The last digits differ because the methods add the numbers in a different order, and floating-point addition is not associative.

On the same laptop, (arr * arr).sum() took 0.39 ns per element and arr @ arr, a dot product handed to an optimized linear-algebra library, 0.18 ns. Compare that with 19.84 ns for the loop. The data is contiguous, the loop body is a few machine instructions, and the processor handles several doubles per instruction. arr * arr also writes a temporary array of a million products before summing it, which the dot product avoids.

And the trap: for x in arr over the NumPy array took 76.38 ns per element. Each arr[i] read creates a new numpy.float64 object, and arithmetic on such scalars is slower than on plain floats. A NumPy array is fast only when Python never touches its elements one by one. The topic NumPy arrays teaches how to write whole computations that way.

Compiled code and the next limit

Sometimes the hot loop does not fit array operations: each step depends on the previous one, it branches on the data, or the intermediate arrays would not fit in memory. Then compile that one function. The options, from least to most effort:

  • numba compiles a function marked @numba.njit to machine code on its first call. It handles numbers, NumPy arrays and plain loops, a subset of Python. Each release supports specific Python and NumPy versions, so check yours.
  • Cython compiles a Python-like language with optional C type declarations into an extension module. Typed loops run at C speed. It needs a C compiler and a build step.
  • An extension in C, C++ or Rust (pybind11, nanobind, PyO3): the most control and the most work. Most of NumPy and PyTorch is written this way.
  • PyPy, another Python implementation with a JIT, runs unchanged pure-Python loops several times faster, but lags behind CPython's versions and supports C extensions less well.

CPython's own JIT is not yet one of these options: in 3.14 it is experimental and off by default.

The whole topic in one line: profile, bound the gain, fix the data structure, trim the hot loop, move numerical loops into NumPy, and compile one function only when nothing else works.

All of this used one processor core. This laptop has eight (os.cpu_count() is 8), and a CPU-bound Python program uses one of them. Many programs also spend their time waiting for files, databases or servers rather than computing. The next topic, Concurrency: threads, processes and asyncio, asks how to use the other cores and how to wait for many things at once, and what the global interpreter lock has to do with both.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.