liveBook · Manning

Tracemalloc

As explained in Fast by Default

tracemalloc is Python's standard-library module for tracing memory allocations and comparing allocation snapshots.

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

How Fast by Default covers it

How deep it goes
Explains snapshot comparison, line-level statistics, and repeated-run interpretation, but does not detail tracemalloc internals.
Examples
Uses batch processing, repeated requests, line-level allocation output, and accumulating request data, connections, response bodies, or cache entries.
What it assumes
Assumes Python code and basic awareness of allocations, garbage collection, requests, and resource cleanup.
What you can do after
Diagnose/debug with it by comparing snapshots and identifying allocation sites whose counts and sizes grow over repeated runs.
How it connects
Connects memory profiling with memory leaks, garbage collection, request-scoped data, database connections, HTTP responses, and caches.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast by Default. The section links point to the parts of the book it draws on.