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 seentokenize 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:
- Do less work: a better algorithm or data structure.
- Do the remaining work in fewer interpreter steps: fewer calls in the hot loop, built-ins, comprehensions.
- 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.