Memory profiling
P34.profiling.02 · Audience: guest, it-ml, language-pro · Prerequisites: Find the hot spot first
Speed is not the only cost. A program that allocates too much slows down — more
garbage collection, worse cache behaviour — and can run out of memory entirely.
The same measure-first discipline applies: tracemalloc profiles allocations
so you can see how much memory your code uses and prove which of two designs is
cheaper.
ⓘ Concept: tracemalloc records where memory comes from
tracemalloc.start() and the runtime records every allocation. tracemalloc.get_traced_memory() returns (current, peak) in bytes — current is what is still live, peak is the high-water mark reached while the code ran. For comparing two implementations, peak is the number to watch. Always stop() when you are done.Why it matters — Time profiling can't tell you a list is quietly eating a gigabyte — allocation profiling can.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
1 graded rung · ~15 minMeasure the peak memory of a builder with tracemalloc, and use it
to prove the slots payoff.
Rung 1 — measure peak memory (tracemalloc)
Loading exercise…
You can now find both the slow function and the memory hog. The optimisation
track is where you act on what the profile told you — starting with the change
that gives the biggest win: the algorithm.
Where next?
This module unlocks
Go up a level