Sub topic 15
Measuring memory use in practice
This chapter assumes you can read Big O notation, know the difference between input space and auxiliary space, and can write basic Python. An analytical estimate tells you how memory grows. A measurement tells you whether your estimate matches what the interpreter does. Use both.
Why measure at all
Big O hides constants. A list of 100,000 integers and a list of 100,000 small objects are both O(n), yet they can differ in size by a factor of ten or more. Measuring shows the real cost and catches hidden copies that you missed while reading the code.
Reading current and peak memory with tracemalloc
The standard library module tracemalloc traces memory blocks allocated by Python code. It reports two numbers in bytes: the current amount allocated, and the peak since tracing started.
import tracemalloc
tracemalloc.start()
data = [i for i in range(100_000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(current, peak)The exact numbers depend on the interpreter version and platform, so treat them as relative values. Do not compare them with figures from another machine.
Checking a Big O estimate
A good test is to run the same function at several input sizes and see how the peak grows. If the space is O(n), doubling n should roughly double the peak. If it is O(1), the peak should stay flat.
import tracemalloc
def peak_bytes(func, n):
tracemalloc.start()
func(n)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def squares_list(n):
return sum([i * i for i in range(n)])
def squares_gen(n):
return sum(i * i for i in range(n))
for n in (10_000, 20_000, 40_000):
print(n, peak_bytes(squares_list, n), peak_bytes(squares_gen, n))The list version should show a peak that grows with n. The generator version should stay small and nearly constant, because it never holds more than one value at a time.
Common errors
- Measuring once. One size tells you a number, not a growth rate. Always use at least three sizes.
- Ignoring the input.
tracemalloconly counts memory allocated afterstart(). If the input was built earlier, it is not counted, so you see auxiliary space only. Build the input before starting if that is what you want to measure. - Expecting recursion depth to show up as lists. Stack frames are real memory, but a deep recursion can fail with
RecursionErrorbefore memory becomes a problem. Python's default limit is about 1,000 frames. - Trusting tiny inputs. Small sizes are dominated by fixed overhead, so the growth trend is hidden. Pick sizes large enough that the signal is clear.
Summary of the method
- Write down your Big O estimate for auxiliary space.
- Build the input first, then start tracing.
- Record the peak at three or more input sizes.
- Compare how the peak scales with n.
- If it disagrees with your estimate, search for slices, copies, string concatenation, or recursion depth.
Exercise
You measure a function at n = 1,000, 2,000 and 4,000 and get peaks of 8 KB, 16 KB and 32 KB. What space complexity does this suggest, and what would a flat peak of about 1 KB at all three sizes suggest instead?
Show answer
Doubling n doubles the peak, which suggests O(n) space. A flat peak at all three sizes suggests O(1) auxiliary space.
Exercise
A function takes a large list as input and you call tracemalloc.start() after the list is built. Does the reported peak include the list? What does this mean for the numbers you read?
Show answer
No. tracemalloc counts only allocations made after start(), so the input list is excluded. The peak reflects auxiliary space, the extra memory the function allocates.