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
- CPython Reference Counting
- The Garbage Collector and Cyclic References
- Profiling with cProfile and line_profiler
- Memory Profiling with tracemalloc