Sub topic 8
Finding memory hogs with tracemalloc
This chapter assumes you can run Python scripts, read a profiler report, and use lists, dicts, and generators. Time is not the only cost in a program. A script that finishes quickly but holds gigabytes of data can be killed by the operating system or slow down other work on the machine. The standard library module tracemalloc shows where your Python code allocates memory.
What tracemalloc measures
tracemalloc hooks into Python's memory allocator and records the line of code that requested each block of memory. It tracks memory allocated by Python objects, not memory used by the interpreter itself or by C libraries that bypass Python's allocator. Treat its numbers as a guide to your own code, not as the total shown by your operating system.
Tracing adds overhead, so you turn it on only while investigating. It must be started before the allocations you want to see. Memory allocated earlier is invisible to it.
A first snapshot
A snapshot is a copy of the allocation records at one moment. You group the records by file, by line number, or by full traceback, then sort them by size.
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 a file and line number, the total size of live allocations from that line, how many blocks there are, and the average block size. The list comprehension line should appear at the top, since it created 100,000 string objects and the list that holds them.
Current and peak usage
Sometimes you only need to know how much memory a block of code needs. get_traced_memory() returns the current and peak sizes in bytes since tracing started.
import tracemalloc
tracemalloc.start()
squares = [i * i for i in range(200_000)]
current, peak = tracemalloc.get_traced_memory()
print(f"current: {current / 1024:.0f} KiB, peak: {peak / 1024:.0f} KiB")
tracemalloc.stop()The peak matters most. A program can free memory later and still crash at the moment its usage is highest.
Comparing two snapshots
A leak or a growing cache shows up as a difference between two points in time. Take one snapshot before the suspect code and one after, then call compare_to.
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 diff in after.compare_to(before, "lineno")[:3]:
print(diff)The output lists the lines whose memory grew the most, with the size change shown as a plus or minus value. In a long-running service you would take the snapshots minutes apart and look for lines that keep growing.
Common fixes
Once you know which line holds the memory, the usual remedies are:
- Use a generator instead of a list when you only need to loop over the values once.
- Read files line by line instead of loading the whole file.
- Drop references to large objects you no longer need, so they can be freed.
- Put a size limit on caches, for example with
lru_cache(maxsize=...). - Store large numeric data in compact structures such as NumPy arrays.
Common errors
- Starting tracing too late, so the allocation you care about is not recorded.
- Comparing
tracemalloctotals with the memory figure fromtopor Task Manager. The two measure different things. - Leaving tracing on in production code. It slows the program and uses extra memory itself.
- Reading a single snapshot when the real problem is growth. Use
compare_tofor that.
Exercise
You suspect a web service slowly leaks memory over several hours. Which tracemalloc approach fits best, and why?
Show answer
Start tracing early, take a snapshot at one time and another snapshot later, then use compare_to on the later snapshot. A single snapshot only shows what is held now, while the comparison shows which lines keep growing, and growth is the sign of a leak.
Exercise
What does the peak value from tracemalloc.gettracedmemory() tell you that the current value does not?
Show answer
It gives the highest memory use since tracing began. A program may free memory before you read the current value, but the peak shows the most memory it needed, which is what decides whether it fits on the machine.