Memory profiling
P34.profiling.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Find the hot spot first
Where next?
This module unlocks
Go up a level
P34.profiling.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Find the hot spot first
This module unlocks
Go up a level
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.
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 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.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Measure the peak memory of a builder with tracemalloc, and use it
to prove the slots payoff.
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.
Loading your notes...