brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's tracemalloc shows which lines are eating your memory

Python
~/tips/tip-python-tracemalloc-top-lines

import tracemalloc

Find the lines of code that allocate the most memory in a Python program.

When a Python process grows and you don’t know why, tracemalloc from the standard library can point at the lines that allocated the memory.

import tracemalloc

tracemalloc.start()

data = [str(i) * 10 for i in range(100_000)]   # the code you suspect

snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:5]:
    print(stat)

The output lists the top lines with their file, line number, total size and number of blocks, something like tm.py:5: size=9560 KiB, count=100001. That’s usually enough to see which list or cache is the problem.

For a leak that builds up slowly, take two snapshots a while apart and compare them with snapshot2.compare_to(snapshot1, "lineno"). Then you only see what grew in between, not everything that was loaded at startup. tracemalloc.get_traced_memory() gives the current and peak size if you only want a number.

You can also switch it on without editing code by running python3 -X tracemalloc script.py and taking snapshots where you need them.

Tracing costs speed and memory of its own, so I’d only turn it on while hunting. It also only sees memory Python itself allocates. Memory grabbed by a C library inside an extension, like a big image buffer, won’t show up.

Further reading: tracemalloc

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link