On this page
  1. tracemalloc
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Comparing Two Heap Snapshots to Spot a Memory Leak
  7. 2. Multi-Frame Call Stacks (tracemalloc.start(10))
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

tracemalloc

Prev: traceback | Up: stdlib_module | Next: tty
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — tracemalloc
Tags: #public #python3 #stdlib


Import

import tracemalloc

Overview

Built-in Python heap memory profiler (start, stop, take_snapshot, get_traced_memory) that records the exact file and line number where Python memory blocks were allocated. Reach for tracemalloc to pinpoint memory leaks, compare before/after heap snapshots, and verify peak memory budgets in tests.

Quick Start

import tracemalloc

tracemalloc.start()
data = [i for i in range(10_000)]
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()

assert peak >= current > 0

Implementation Walkthrough

1. Comparing Two Heap Snapshots to Spot a Memory Leak

import tracemalloc

tracemalloc.start()
snap1 = tracemalloc.take_snapshot()

leaked = ["x" * 1000 for _ in range(500)]
snap2 = tracemalloc.take_snapshot()

top_diffs = snap2.compare_to(snap1, "lineno")
assert len(top_diffs) >= 1 and top_diffs[0].size_diff > 0
tracemalloc.stop()

2. Multi-Frame Call Stacks (tracemalloc.start(10))

Pass nframe > 1 to start(nframe) when you need the full call chain (not just the leaf allocation line) via snapshot.statistics("traceback").

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes