Sub topic 12
Finding allocations with tracemalloc
This chapter assumes you can read the output of sys.getsizeof and gc.collect(). It also assumes you know that CPython frees most objects through reference counting and uses a small-object allocator. You do not need to know how tracemalloc is implemented. You need to know how to use it and what its numbers mean.
What tracemalloc answers
sys.getsizeof tells you how big one object is. It does not tell you which line of your program created the memory that is piling up. tracemalloc is a standard-library module that answers that question. It hooks into CPython's memory allocators and records, for each live memory block, the traceback of the code that requested it.
From that record you can ask:
- Which source lines currently hold the most memory?
- What changed between two points in time?
- What is the highest memory use my program reached?
- Which call stack led to a given allocation?
Starting the tracer
Tracing is off by default because it costs time and memory. You turn it on in one of three ways:
- Call
tracemalloc.start()in your code. - Run
python -X tracemalloc script.py. - Set the environment variable
PYTHONTRACEMALLOC=1before launching Python.
The number you pass is the number of stack frames stored per allocation. The default is 1, which records only the line that made the allocation.
Your first snapshot
A snapshot is a frozen copy of the allocation records at one moment. statistics("lineno") groups the records by source line and sorts them by size, largest first.
import tracemalloc
tracemalloc.start()
data = [str(i) for i in range(100_000)]
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:3]:
print(stat)Each printed line shows the file and line number, the total size in KiB, the number of blocks, and the average block size. The list comprehension line should be at or near the top, because it created 100,000 string objects and the list that holds them.
A snapshot contains only memory that is alive when you take it. If an object was allocated and freed before the snapshot, it does not appear.
Grouping: lineno, filename, and traceback
The second argument to statistics() is the grouping key.
| Key | Groups allocations by | Use it when |
|---|---|---|
| `"filename"` | Source file | You want a coarse view of which module is heavy |
| `"lineno"` | File and line number | You want the exact line (the usual choice) |
| `"traceback"` | The full recorded call stack | The same line is called from many places and you need to know which caller matters |
Grouping by "traceback" is only useful if you stored more than one frame. The next example starts tracing with a depth of 5.
import tracemalloc
def build():
return [str(i) for i in range(50_000)]
def main():
return build()
tracemalloc.start(5)
data = main()
snapshot = tracemalloc.take_snapshot()
top = snapshot.statistics("traceback")[0]
print(f"{top.count} blocks, {top.size / 1024:.0f} KiB")
for line in top.traceback.format():
print(line)The output lists the frames that led to the allocation, so you can see that main called build. With the default depth of 1 you would see only the comprehension line inside build.
Storing more frames costs more memory per allocation. Pick the smallest depth that answers your question.
Comparing snapshots to find growth
One snapshot tells you where memory is. Two snapshots tell you where memory is growing. compare_to() returns a list of StatisticDiff objects sorted by the absolute size change.
import tracemalloc
tracemalloc.start()
before = tracemalloc.take_snapshot()
cache = {}
for i in range(50_000):
cache[i] = "value-" + str(i)
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:3]:
print(stat)Each line reports the current size, the change since the first snapshot (+ or -), and the same for block counts. Lines with a large positive diff that keep growing across repeated comparisons are your leak candidates.
The usual workflow looks like this:
Run the workload more than once before you decide something leaks. A cache filling up, a lazily imported module, or an interned string table all show growth the first time and then level off. A leak keeps growing.
Current and peak memory
For a quick number without a full snapshot, use get_traced_memory(). It returns a pair: the current traced size and the peak since tracing started, both in bytes.
import tracemalloc
tracemalloc.start()
big = [bytes(1000) for _ in range(10_000)]
current, peak = tracemalloc.get_traced_memory()
print(f"with list: current={current / 1e6:.1f} MB, peak={peak / 1e6:.1f} MB")
del big
current, peak = tracemalloc.get_traced_memory()
print(f"after del: current={current / 1e6:.1f} MB, peak={peak / 1e6:.1f} MB")
tracemalloc.reset_peak()
current, peak = tracemalloc.get_traced_memory()
print(f"after reset: current={current / 1e6:.3f} MB, peak={peak / 1e6:.3f} MB")The peak stays high after del big, because it records the maximum. reset_peak() (Python 3.9 and later) sets the peak back to the current value. This lets you measure the peak of one function call by resetting before it and reading after it.
Peak memory often matters more than the final number. A function that builds a large temporary list and then returns a small result can still push your process past a memory limit.
Filtering out noise
Snapshots include allocations made by the import system and by tracemalloc itself. filter_traces() returns a new snapshot with matching traces included or excluded. A Filter takes a first argument, inclusive, then a filename pattern.
import tracemalloc
tracemalloc.start()
records = [{"id": i, "name": f"item-{i}"} for i in range(20_000)]
snapshot = tracemalloc.take_snapshot()
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<frozen importlib._bootstrap_external>"),
tracemalloc.Filter(False, tracemalloc.__file__),
))
for stat in snapshot.statistics("lineno")[:3]:
print(stat)Use Filter(True, "myapp/*") to keep only your own package. The pattern supports * wildcards, so "myapp/*" matches every file under that directory.
What the numbers do and do not include
Three limits explain most of the confusion people have with tracemalloc output.
- It reports traced Python allocations, not process size. The resident memory shown by your operating system also includes the interpreter itself, loaded C libraries, memory held by
pymallocarenas that are not yet returned to the OS, and fragmentation. The traced total is normally lower. - It sees only allocations that go through Python's allocator hooks. A C extension that calls the C library's
mallocdirectly is not counted. Some well-known libraries report their buffers totracemallocand some do not. - It has overhead. Tracing slows the program and the records themselves use memory.
tracemalloc.get_tracemalloc_memory()returns how many bytes the tracer is using for its own bookkeeping. Treat timings under tracing as unreliable.
Because of the first limit, a flat tracemalloc total with a growing process size points away from Python objects. Suspect native extensions, or memory the allocator holds but has not returned to the OS.
Saving snapshots for later
A snapshot can be written to disk with snapshot.dump("file.snap") and loaded with tracemalloc.Snapshot.load("file.snap"). This lets you capture data from a running service and analyze it elsewhere. It also lets you compare a snapshot from this morning with one from this evening.
Common mistakes
- Taking only one snapshot of a suspected leak. A single snapshot shows large memory, not growing memory. Compare at least two.
- Starting tracing too late. Allocations made before
start()are not in the records, so a leak that begins at startup is partly hidden. - Reading
size_difffrom one run. One-time growth looks the same as a leak until you repeat the workload. - Forgetting that tracing changes timing. Race-dependent or performance-dependent bugs may behave differently under the tracer.
- Holding the snapshot variable. Snapshots are memory too. Delete old ones, or save them to disk and drop the reference.
Exercise
You run a service that handles requests in a loop. You call tracemalloc.start(), take snapshot A, process 1,000 requests, take snapshot B, and see that after.compare_to(before, "lineno") reports +4 MiB on a line inside a cache-filling function. Is this a leak? What would you do next, and what would you look for?
Show answer
One comparison cannot tell you. Growth can be a cache warming up. Process another batch of requests, take snapshot C, and compare C to B. If the same line grows by a similar amount again, it is a leak candidate, because the data is not levelling off. Then start tracing with a larger frame depth (for example tracemalloc.start(10)) and group by "traceback" to see which callers allocate the data. Finally, find what keeps references to those objects, such as a module-level dict with no eviction, and fix that owner.
Exercise
A process shows 800 MB resident memory in the operating system's monitor, but tracemalloc.gettracedmemory() reports a current size of about 120 MB. Name two reasons the numbers can differ.
Show answer
Any two of these: memory used by the interpreter and loaded libraries that tracemalloc does not trace; allocations made directly by C extensions through the C library's malloc, which bypass Python's allocator hooks; pymalloc arenas or freed heap memory that CPython or the C library has not returned to the operating system; fragmentation; and objects allocated before tracing started.