Memory profiling

P34.profiling.02 · Audience: guest, it-ml, language-pro · Prerequisites: Find the hot spot first

Real LLM grading for this pageLLM grading (this page):

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.

Step 1 / 3 — Trace allocations
ⓘ Concept: tracemalloc records where memory comes from
Call 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.

Images, PDF or text. Kept on this device only.
Keeping your files on this device

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.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

1 graded rung · ~15 min

Measure 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.

My notes on this module

Loading your notes...

Memory profiling — TransformerLab