Python 3.4+tracemallocfunction
tracemalloc.take_snapshot()
snapshots
Takes a snapshot of all current allocation traces and returns a Snapshot object for analysis.
Syntax
snapshot = tracemalloc.take_snapshot()
Raises RuntimeError if tracing has not been started. A snapshot is a copy at call time: a single snapshot shows only the current picture, while a leak shows up as the difference of two snapshots via compare_to(). A snapshot of a large program itself takes noticeable memory and time — do not take one inside a hot loop.
Examples
import tracemalloc
try:
tracemalloc.take_snapshot()
except RuntimeError as e:
print(type(e).__name__) # → RuntimeError
import tracemalloc
tracemalloc.start()
words = [str(i) * 10 for i in range(5000)]
snap = tracemalloc.take_snapshot()
top = snap.statistics('lineno')[0]
print(top.traceback[0].lineno) # → 3
tracemalloc.stop()
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy