Sub topic 8
Finding memory hogs with tracemalloc
This chapter assumes you can read a cProfile report, as covered earlier in the tutorial. It also assumes you are comfortable with comprehensions, generators, and dictionaries. You need Python 3.9 or newer. tracemalloc is in the standard library, so there is nothing to install.
Why memory needs its own tool
CPU profilers answer "where does the time go?" They do not tell you why a process grows to several gigabytes, why a container gets killed for exceeding its memory limit, or why a long-running service slowly gets bigger. Memory also affects speed. A program that builds huge intermediate lists spends time allocating, copying, and paging them.
tracemalloc is Python's built-in memory tracer. Once started, it records where each memory block was allocated, meaning the file, the line, and optionally the call stack. You can then ask which lines hold the most memory, and which lines gained memory between two points in time.
What tracemalloc sees and what it misses
tracemalloc hooks Python's memory allocators. That has two consequences:
- It sees Python objects such as lists, dicts, strings, and instances. It also sees memory from extension modules that report through Python's allocator. NumPy does this, so array buffers appear in the output.
- It does not see memory that a C library obtains directly with
malloc, and it does not report the process's total resident size. The number fromtracemallocis usually lower than whattopor Task Manager shows.
Use tracemalloc to find which of your Python lines allocate. Use operating system tools to find out how big the process is.
The first snapshot
A snapshot is a frozen copy of the allocation records at one moment. Start tracing before the allocations you want to study. Memory allocated earlier is not attributed to any line.
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 entry has the form file:line: size=..., count=..., average=.... The top entry should point at the list comprehension line. It holds the list's pointer array plus 100,000 small string objects, which comes to several MiB on a 64-bit CPython build.
statistics() takes a grouping key:
| Key | Groups allocations by | Use it to |
|---|---|---|
| `"filename"` | Source file | See which module is heavy |
| `"lineno"` | File and line | Find the exact statement |
| `"traceback"` | Full call stack | Find which caller triggered the allocation |
Start with "filename" for a program you do not know, then narrow to "lineno".
Current memory and peak memory
A snapshot shows what is alive right now. A program can still run out of memory because of a short spike that has been freed by the time you look. For that, ask for the traced total and the peak:
import tracemalloc
def sum_squares_list(n):
return sum([i * i for i in range(n)])
def sum_squares_generator(n):
return sum(i * i for i in range(n))
def measure_peak(func, n):
tracemalloc.start()
func(n)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
for func in (sum_squares_list, sum_squares_generator):
peak = measure_peak(func, 1_000_000)
print(f"{func.__name__}: peak {peak / 1_048_576:.2f} MiB")get_traced_memory() returns (current, peak) in bytes, counted since tracing started. The list version builds one million integers and a pointer array before sum consumes them. The generator version produces one value at a time. You should see the list version peak at tens of MiB and the generator version stay far below 1 MiB. The two functions return the same number, so only the memory profile differs.
Call tracemalloc.reset_peak() to restart peak tracking without stopping the trace. This is useful for measuring several phases of one program separately.
Finding growth by comparing snapshots
The most useful tracemalloc technique is to take two snapshots and subtract them. A line whose allocations keep growing while the workload stays steady is a leak candidate. Typical causes are a cache with no size limit, a list that only receives appends, or a registry that never removes entries.
import tracemalloc
cache = {}
def handle_request(i):
cache[i] = f"request-{i}" * 100
tracemalloc.start()
for i in range(1_000):
handle_request(i)
before = tracemalloc.take_snapshot()
for i in range(1_000, 2_000):
handle_request(i)
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:3]:
print(stat)compare_to returns entries sorted by the size difference. Each entry shows the new total, then + or - followed by the change in size and count. The line inside handle_request should come first, with roughly a thousand new blocks. The cache gained one string per request and never released any.
In a real service, take the first snapshot after a warm-up period. Startup allocations such as imports and configuration would otherwise show up as growth. Take the second snapshot after the workload has run for a while.
flowchart TDThe diagram below shows the full workflow.
Seeing who called the allocator
Line-level results can be unhelpful when the allocation happens inside a shared helper. If every part of the program calls make_record(), the top line is always inside make_record(). To see the callers, record more stack frames and group by "traceback":
import tracemalloc
tracemalloc.start(10)
def make_record(i):
return {"id": i, "name": f"user-{i}"}
def load_users():
return [make_record(i) for i in range(20_000)]
def load_admins():
return [make_record(i) for i in range(2_000)]
users = load_users()
admins = load_admins()
snapshot = tracemalloc.take_snapshot()
top = snapshot.statistics("traceback")[0]
print(f"{top.size / 1024:.0f} KiB in {top.count} blocks")
for line in top.traceback.format():
print(line)tracemalloc.start(10) keeps up to 10 frames per allocation. The default is 1, which gives only the allocating line. The printed stack should show that the largest group came through load_users, not load_admins. The same effect is available without editing code. Set the environment variable PYTHONTRACEMALLOC=10 or run python -X tracemalloc=10 script.py. Either way, tracing begins at interpreter startup, so import-time allocations are also recorded.
Filtering out noise
Snapshots include allocations from the standard library, the import system, and tracemalloc itself. Remove them with filter_traces. A Filter takes an inclusive flag and a filename pattern with * wildcards.
import tracemalloc
tracemalloc.start()
data = [str(i) for i in range(50_000)]
snapshot = tracemalloc.take_snapshot()
snapshot = snapshot.filter_traces([tracemalloc.Filter(True, __file__)])
for stat in snapshot.statistics("filename"):
print(stat)Filter(True, pattern) keeps only matching files, and Filter(False, pattern) drops them. For a real application, a pattern such as "*/myapp/*" keeps only your own package. filter_traces returns a new snapshot, so the original is unchanged.
Cost and common mistakes
Tracing has a price. Every allocation is recorded, so the program runs slower and uses more memory. The cost grows with the number of frames kept. Use tracemalloc in a test or staging run, and start with nframes=1. Raise it only when you need callers.
These mistakes come up often:
- Starting too late. Memory allocated before
start()is invisible, and an object that was allocated earlier but freed during tracing can confuse the totals. Start early or usePYTHONTRACEMALLOC. - Comparing against the wrong baseline. Without a warm-up, the first snapshot lacks caches that fill lazily, and the diff looks like a leak.
- Treating a growing diff as proof of a leak. A bounded cache or a buffer that is still filling also grows. Take a third snapshot later. A true leak keeps growing at a steady rate. A bounded structure levels off.
- Reading peak from a snapshot. Snapshots show live memory only. Use
get_traced_memory()for the peak. - Expecting totals to match the operating system. Memory freed by Python is often kept by the allocator for reuse, and untracked C allocations are not counted.
Fixing what you find
Once the output points to a line, the fix usually follows from the structure:
- Replace a list with a generator when the values are consumed once, as in the peak example.
- Put a size limit on any cache.
functools.lru_cache(maxsize=1024)does this for function results, and itscache_info()shows whether the limit is being hit. - Drop references you no longer need, for example by setting a large local to
Noneor by closing over less data. - Use compact types. A NumPy array of integers is far smaller than a list of Python
intobjects, and__slots__shrinks instances of classes that you create in large numbers.
After each change, repeat the same measurement. A fix is confirmed when the peak or the diff drops, not when the code looks more efficient.
Summary of the API
| Call | Purpose |
|---|---|
| `tracemalloc.start(nframes=1)` | Begin tracing, keeping `nframes` stack frames |
| `tracemalloc.take_snapshot()` | Freeze the current allocation records |
| `snapshot.statistics(key)` | Totals grouped by `filename`, `lineno`, or `traceback` |
| `snapshot.compare_to(old, key)` | Differences between two snapshots |
| `snapshot.filter_traces(filters)` | Keep or drop traces by filename |
| `tracemalloc.get_traced_memory()` | `(current, peak)` in bytes |
| `tracemalloc.reset_peak()` | Restart peak tracking |
| `tracemalloc.stop()` | Stop tracing and clear stored data |
Exercise
A web service's memory grows by about 50 MiB per hour. You run it under tracemalloc, take a snapshot right after startup, and another after an hour. The comparison lists many lines with large positive differences, including lines that load configuration and compile regular expressions. What should you change about the procedure, and why?
Show answer
Take the first snapshot after a warm-up period instead of right after startup. Configuration loading, imports, and lazily built caches are one-time allocations, so they appear as growth in the diff even though they are not leaks. After the warm-up, take two snapshots some time apart under steady load, and compare those. Entries that keep growing between them are leak candidates. A third snapshot later can confirm whether the growth continues or levels off.
Exercise
You change a function to return a list instead of a generator. The function's results are identical, but a test run now fails a memory limit. Write the two lines of code that would show the difference in peak memory for a call, and explain why a snapshot taken after the call would not show it.
Show answer
Call tracemalloc.start() before the call, then after it run _, peak = tracemalloc.get_traced_memory(), and compare the peak values for the two versions. A snapshot taken after the call shows only memory that is still alive. The list is freed once the caller finishes with it, so the temporary spike is gone by then. The peak value records the highest point reached while tracing.