Python 3.4+tracemallocterm
tracemalloc.Statistic
snapshots
One row of snapshot statistics: total size, block count, and the traceback of where the memory was allocated.
Syntax
for stat in snapshot.statistics('lineno'): stat.size, stat.count, stat.traceback
Snapshot.statistics() returns a list of Statistic already sorted by size in descending order, so [0] is the top consumer. size is in bytes, while str(stat) prints it in KiB together with the average block size. When grouped by 'lineno' the traceback holds a single frame; the full call chain needs 'traceback' with start(nframe>1).
Examples
import tracemalloc
tracemalloc.start()
items = [str(i) * 10 for i in range(10_000)]
stat = tracemalloc.take_snapshot().statistics('lineno')[0]
print(stat.traceback[0].lineno, stat.count >= 10_000) # → 3 True
print(stat) # → ? путь, размер в KiB и среднее зависят от машины
tracemalloc.stop()
See also
Open in the full glossarydocs.python.orgReport an inaccuracy