Python Performance: Profiling, Caching, Memory
Speed work in Python rarely fails because someone chose the wrong algorithm on purpose. It fails because the slow line was guessed at, not measured. A script that feels sluggish is usually dominated by one hot loop, one repeated disk read, or one collection that grows far larger than anyone expected. This lesson walks through a repeatable order of operations: find the cost, decide what kind of cost it is, apply the matching lever, and then confirm the improvement with the same measurement you started with.
What You'll Learn
- 1Profile a program with cProfile and read the output without being misled by cumulative time
- 2Choose between memoization, cheaper data structures, and algorithm changes for a given bottleneck
- 3Reduce memory use with __slots__, generators, and streaming instead of eager materialization
- 4Recognize optimizations that look fast in a microbenchmark but lose in real workloads
Measurement before modification
Python gives you three levels of timing, and picking the wrong one wastes an afternoon. time.time() is wall-clock and jumps when the system clock is adjusted. time.perf_counter() is monotonic and has the highest resolution, so it is the right default for benchmarking a block of code. time.process_time() counts CPU seconds for the current process, which tells you whether a slow run was actually computing or simply waiting on I/O.
For anything longer than a few lines, a profiler beats manual timing because it attributes cost to lines rather than to your assumptions. cProfile reports call counts, total time, and cumulative time per function. Cumulative time includes callees, so a function with a huge cumulative number may be innocent: it might just be the entry point that touches every slow helper. Sort by internal time to find functions that burn cycles themselves.
import cProfile
import pstats
import io
import time
def build_index(records):
index = {}
for r in records:
index.setdefault(r["category"], []).append(r["id"])
return index
def summarize(index):
return {k: len(v) for k, v in index.items()}
def workload(n=200_000):
records = [
{"id": i, "category": f"cat-{i % 97}"}
for i in range(n)
]
return summarize(build_index(records))
start = time.perf_counter()
result = workload()
print("wall", round(time.perf_counter() - start, 4), "cats", len(result))
stream = io.StringIO()
cProfile.run("workload()", "prof.out")
pstats.Stats("prof.out", stream=stream).sort_stats("tottime").print_stats(8)
print(stream.getvalue())
Run this once before changing anything. The profile usually names a single function that accounts for most of the internal time, and often it is a place where a list comprehension, a string format, or a repeated lookup does more work than it needs to.
The cost taxonomy: CPU, memory, I/O, contention
Every bottleneck belongs to one of four families, and each has a different cure. CPU-bound work is fixed by better algorithms, fewer interpreter operations, or moving hot code into a library implemented in C. Memory-bound work is fixed by not building the whole structure when a partial one will do. I/O-bound work is fixed by overlap and batching, not by micro-optimizing the parsing that follows. Contention appears when threads fight over a lock or when a shared resource throttles everyone.
| Symptom | Likely family | First fix to try | Common dead end |
|---|---|---|---|
| One core pegged, RAM flat | CPU | Profile, then replace the hot algorithm | Rewriting in another language before profiling |
| Memory climbs until the process dies | Memory | Generators, __slots__, streaming reads | Adding swap or raising a limit |
| Low CPU, long waits on disk or network | I/O | Batch requests, cache, overlap with async | Tuning pure-Python parsing between requests |
| CPU idle, everything queues | Contention | Reduce lock scope, pool the resource | Adding more threads to a serialized section |
Classifying the family first prevents the classic mistake of applying an I/O cure to a CPU problem. Caching a function that is already instant does nothing; overlapping calls that were never blocking does nothing either.
Memoization and when the cache hurts
functools.lru_cache turns a pure function into a cached one, and for recursive work with a small key space the effect is dramatic. Fibonacci is the usual demonstration, but real code benefits from memoizing expensive parsing, database key lookups, and any deterministic transformation called repeatedly with the same arguments.
The cache is only correct if the function is genuinely pure: same inputs, same output, no dependence on time, files, or global state. It is also only useful if the key space is small. A function that takes a list argument is unhashable and raises immediately; a function that takes a long string builds an entry per distinct string and eventually evicts the entries you actually repeat. Watch the hit rate with cache_info() before declaring victory.
from functools import lru_cache
import time
@lru_cache(maxsize=4096)
def parse_config(raw):
result = {}
for line in raw.splitlines():
if line and not line.startswith("#"):
key, _, value = line.partition("=")
result[key.strip()] = value.strip()
return result
lines = "\n".join(f"key{i}=value{i}" for i in range(5000))
start = time.perf_counter()
for _ in range(2000):
parse_config(lines)
print("cached", round(time.perf_counter() - start, 6))
parse_config.cache_clear()
start = time.perf_counter()
for _ in range(2000):
parse_config(lines)
print("uncached", round(time.perf_counter() - start, 6))
print(parse_config.cache_info())
Two details matter in production. Returning a mutable object from a cached function hands every caller the same list or dictionary, so an accidental append corrupts later results. And an unbounded or very large cache grows process memory silently, which converts a CPU problem into a memory problem.
Memory: slots, generators, and lazy structures
CPython instances normally carry a per-object dictionary, which costs memory on every single instance. Declaring __slots__ replaces that dictionary with fixed descriptors, and for classes instantiated millions of times the saving is substantial. The trade-off is that you cannot add undeclared attributes, and subclassing gets stricter, so slots suit data-carrying records rather than open-ended base classes.
The larger win usually comes from refusing to build the list at all. Generator expressions and streaming iteration keep only the current element alive, which lets a program process a file far larger than RAM. The cost is that generators are single-use and cannot be indexed, so anything you need twice must be recomputed or materialized deliberately.
import sys
from dataclasses import dataclass
class Packed:
__slots__ = ("sku", "qty")
@dataclass(slots=True)
class Row:
sku: str
qty: int
print(sys.getsizeof(Packed.__slots__))
def rows(path):
with open(path, encoding="utf-8") as handle:
for line in handle:
sku, qty = line.rstrip("\n").split("\t")
yield sku, int(qty)
def total_qty(path):
return sum(q for _, q in rows(path))
Compare sys.getsizeof of a slotted instance against a dictionary-based one on your own interpreter build, and remember that the dictionary itself also holds references that keep other objects alive.
A worked pass: from symptom to measured fix
Take a concrete case that shows the method end to end. A report job takes eleven seconds and is blamed on Python being slow. The profile immediately shows that the time is not in the arithmetic at all: a membership test against a list of known identifiers accounts for most of the internal time, because the list holds forty thousand entries and runs inside a loop over two hundred thousand records. The fix is not a faster loop; it is a different data structure.
Converting the identifier list into a set before the loop turns each membership test from a linear scan into a hash lookup. The edit is two lines, and the profile after the change confirms that the function which previously dominated the internal time now barely registers. The remaining time is spent in string parsing, which is a different family and would need a different tool, such as a compiled parser or a columnar format, if it ever became the bottleneck again.
The discipline is what matters more than the specific fix. Note the number before editing, classify the cost, apply one change, and record the number after. Teams that skip the before-and-after measurement end up with code that is harder to read and no faster, because the second optimization was applied to a function that was never the problem.
Micro-optimizations, ranked honestly
Once the big costs are gone, a handful of small changes still matter in tight loops. Local variable lookups are faster than global or attribute lookups because the bytecode uses cheaper instructions, so binding append to a name outside a loop does help. Membership testing against a set beats a list, sometimes by orders of magnitude. Joining strings in one call beats repeated concatenation, since strings are immutable and each plus creates a new object.
What does not help is rewriting readable code into a form that confuses the next reader for a two percent gain that a noisy machine cannot even measure. Any optimization worth keeping should show up in a profile, survive a second run, and leave the code at least as clear as you found it.
Common Mistakes
Optimizing a function that appears slow only because its callees are slow
Fix: Sort profiler output by tottime to see where time is spent directly, then decide where to edit
Caching a function whose results depend on mutable external state
Fix: Only memoize pure functions, or include the relevant state in the key and expose a way to invalidate
Building a full list when the consumer only ever iterates once
Fix: Yield values with a generator so peak memory stays constant regardless of input size
Judging an optimization from a single timing run
Fix: Repeat the measurement, compare medians, and confirm the profile actually moved
Best Practices
- Profile before editing and re-profile after, keeping both numbers in the commit message
- Classify the bottleneck as CPU, memory, I/O, or contention before choosing a technique
- Use perf_counter for wall-clock benchmarks and process_time to separate compute from waiting
- Cap caches with maxsize and monitor hit rates rather than assuming the cache is working
- Prefer standard library tools such as cProfile, tracemalloc, and functools before adding dependencies
Interview Questions
Q1: What is the difference between tottime and cumtime in cProfile output?
tottime is time spent inside the function itself, excluding its callees; cumtime includes everything the function called. Sort by tottime to find real hotspots and use cumtime to find expensive call trees.
Q2: When does lru_cache make a program slower or wrong?
It is wrong for impure functions whose output changes without input changes, and it can be slower when the key space is huge, because hashing large keys and evicting entries costs more than recomputing would.
Q3: How would you cut memory for ten million small records?
Use slots or a slotted dataclass to remove per-instance dictionaries, avoid keeping all records at once by streaming with a generator, and choose compact representations such as arrays or tuples when the schema allows it.
Key Takeaways
- Measure with perf_counter and profile with cProfile before touching code
- Match the fix to the bottleneck family: CPU, memory, I/O, or contention
- Memoization requires pure functions and a small key space to pay off
- Slots and generators reduce memory by removing dictionaries and avoiding materialization
- An optimization that cannot be shown in a second profile was probably noise