Sub topic 12
Finding allocations with tracemalloc
This chapter assumes you know how names refer to objects, how sys.getsizeof reports shallow sizes, and how reference counting frees objects. It shows how to find which lines of your program hold memory.
Why a profiler
sys.getsizeof measures one object. It cannot tell you which part of a program is responsible for memory growth. tracemalloc is a standard library module that records where each allocation happened. It stores a traceback for every block of memory that Python allocates, so you can ask which lines hold the most memory right now.
Taking a snapshot
Call tracemalloc.start() before the code you want to examine. Then call take_snapshot() to capture the allocations that are still alive at that moment.
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 names a file and line number, the total size of live memory allocated there, the number of blocks, and the average block size. The list comprehension line should appear near the top, because the strings and the list were allocated there.
Only allocations made after start() are tracked. Objects created earlier are invisible to it.
Grouping the results
statistics() takes a key that controls how allocations are grouped.
| Key | Groups allocations by | Use it to |
|---|---|---|
| `"lineno"` | file and line number | find the exact line |
| `"filename"` | file | find the module |
| `"traceback"` | full call stack | find who called the allocating code |
Grouping by "traceback" only shows more than one frame if you ask for more. Pass a frame count to start(), for example tracemalloc.start(10). The default is 1 frame.
Comparing two snapshots
A single snapshot shows what is large. A leak is something that grows. Take one snapshot before and one after the suspect code, then compare them.
import tracemalloc
cache = []
def handle_request(n):
cache.append("x" * n)
tracemalloc.start()
before = tracemalloc.take_snapshot()
for _ in range(1000):
handle_request(1000)
after = tracemalloc.take_snapshot()
for diff in after.compare_to(before, "lineno")[:3]:
print(diff)Each result shows the size and count of new allocations, with the change since the first snapshot. The line inside handle_request appears at the top because the module-level cache list keeps every string alive.
Current and peak usage
For a quick total, tracemalloc.get_traced_memory() returns a tuple of the current and peak traced sizes in bytes. The peak value is useful for finding temporary spikes that a later snapshot would miss.
import tracemalloc
tracemalloc.start()
temp = [0] * 1_000_000
del temp
current, peak = tracemalloc.get_traced_memory()
print(current < peak) # True: the list is freed, but the peak remembers it
tracemalloc.stop()Common errors
- Starting too late. Memory allocated before
start()is not tracked. Start at the top of the program, or set thePYTHONTRACEMALLOC=1environment variable. - Reading the wrong line. A line is blamed for allocating, not for keeping the memory alive. The real cause is often a container elsewhere that holds a reference. Use a deeper traceback to find the caller.
- Ignoring overhead. Tracing makes the program slower and uses extra memory to store tracebacks. Use it while investigating, not in normal production runs.
- Expecting totals to match the operating system.
tracemalloccounts memory that Python allocates. It does not include memory used by the interpreter itself or by C libraries that bypass Python's allocators.
Exercise
You take a snapshot at startup and another after one hour of running. A line in compare_to shows +50 MiB. Does that prove the line is leaking?
Show answer
No. It shows that the line allocated memory that is still alive, not why it is still alive. It may be a legitimate cache that has reached its working size. Take more snapshots over time. If the line grows steadily, find which container or reference holds the objects, using a deeper traceback from tracemalloc.start(frames).
Exercise
Why does get_traced_memory() return both a current and a peak value?
Show answer
The current value is the memory held now. The peak is the highest value since tracing started or since the last reset. A short spike that was freed before the next snapshot appears only in the peak.