Python › Debugging & Profiling
How do you use memory_profiler (or tracemalloc from the standard library) to identify a memory leak's source in a Python application?
AdvancedAnswer
tracemalloc.start() begins tracking memory allocations by source location; taking two snapshots (tracemalloc.take_snapshot()) before and after a suspected leaking operation, then comparing them with snapshot2.compare_to(snapshot1, 'lineno'), reveals exactly which lines of code are responsible for growing memory usage.
import tracemalloc
tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
run_suspected_leaking_operation()
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, "lineno")
for stat in top_stats[:5]:
print(stat)Real-world example Pinpointing the exact line of code responsible for a service's steadily growing memory usage over time.