Compare Allocation Snapshots with tracemalloc
Core idea
tracemalloc traces Python memory allocations made after tracing starts. Take a baseline snapshot, run a workload, then compare a later snapshot by line or filename. Positive size differences indicate additional traced memory still allocated, not automatically a leak. get_traced_memory gives current and peak traced bytes; native allocations and total process RSS may differ.
import tracemalloctracemalloc.start()try: before = tracemalloc.take_snapshot() blocks = [bytearray(1024) for _ in range(20)] after = tracemalloc.take_snapshot() changes = after.compare_to(before, 'lineno') print(len(blocks), any(s.size_diff > 0 for s in changes))finally: tracemalloc.stop()The live blocks contribute positive differences. Exact byte counts depend on runtime and allocator.
Expected output:
20 TrueInspect current and peak memory
import tracemalloctracemalloc.start()try: payload = bytearray(4096) current, peak = tracemalloc.get_traced_memory() print(len(payload), peak >= current > 0)finally: tracemalloc.stop()print(tracemalloc.is_tracing())Peak is at least the current traced size. Tracing is stopped after use.
Expected output:
4096 TrueFalseCommon mistake
Do not interpret every positive snapshot difference as a leak. Warm caches and intentionally retained data are normal; test repeated workloads with the same retention policy. Tracing overhead itself affects measurements.
Practice
Compare snapshots before and after retaining 100 small records, then after releasing them. Report traced changes rather than claiming total process memory savings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tracemalloc
Check your understanding of tracemalloc.
What is printed?
import tracemalloctracemalloc.start()print(tracemalloc.is_tracing())tracemalloc.stop()What is printed?
import tracemalloctracemalloc.start()a=bytearray(1000)c,p=tracemalloc.get_traced_memory()print(p>=c)tracemalloc.stop()What does a positive size_diff prove?
What should you do after temporary tracing?