tracemalloc is Python’s standard-library module for tracing memory allocations and comparing snapshots. It helps distinguish normal garbage-collected memory from allocations that accumulate across requests or repeated operations. section 7.2.4
Use a snapshot-compare workflow to investigate suspected leaks:
- Start tracing and capture a snapshot before the operation. section 7.2.4
- Run the batch or request-handling operation, then capture a second snapshot. section 7.2.4
- Compare snapshots by line number and inspect new allocation counts and memory sizes. section 7.2.4
- Repeat the operation about ten times: proportional growth indicates accumulation, while stable totals suggest normal cleanup. section 7.2.4
Listing 7.4 Python memory profiling with tracemalloc
import tracemalloc
tracemalloc.start() #A
snapshot_before = tracemalloc.take_snapshot() #B
process_batch(data) #C
snapshot_after = tracemalloc.take_snapshot() #D
top_stats = snapshot_after.compare_to( #E
snapshot_before, 'lineno'
)
for stat in top_stats[:10]: #F
print(stat)The listing shows the complete tracemalloc sequence: start tracing, take before-and-after snapshots, compare by line number, and print the largest differences. section 7.2.4
