0Pricing
Python Academy · Lesson

Memory Profiling with tracemalloc

Track memory allocations and find leaks with tracemalloc.

What Is tracemalloc?

tracemalloc is a standard library module that tracks Python memory allocations by file and line number.

import tracemalloc

tracemalloc.start()

x = [i for i in range(100_000)]

current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()

print(f"Current: {current/1024:.1f} KB")
print(f"Peak:    {peak/1024:.1f} KB")

Taking Snapshots

A snapshot captures all current allocations at a point in time. Compare two snapshots to find what was allocated between them.

import tracemalloc

tracemalloc.start()

snap1 = tracemalloc.take_snapshot()

data = [{"key": str(i)} for i in range(10_000)]

snap2 = tracemalloc.take_snapshot()

stats = snap2.compare_to(snap1, "lineno")
for stat in stats[:5]:
    print(stat)

All lessons in this course

  1. CPython Reference Counting
  2. The Garbage Collector and Cyclic References
  3. Profiling with cProfile and line_profiler
  4. Memory Profiling with tracemalloc
← Back to Python Academy