Memory Profiling with tracemalloc
Track memory allocations and find leaks with tracemalloc.
Memory Profiling with tracemalloc is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)Filtering Snapshots
Filter stats to only show your application's code, excluding the standard library.
import tracemalloc
tracemalloc.start()
leak_function()
snap = tracemalloc.take_snapshot()
filters = [tracemalloc.Filter(True, "*/myapp/*")]
stats = snap.filter_traces(filters).statistics("lineno")
for stat in stats[:10]:
print(stat)Top Allocators
Use snapshot.statistics("lineno") or "traceback" to see the top memory consumers by line or full traceback.
import tracemalloc
tracemalloc.start(nframe=10) # track 10 frames deep
big_list = [i**2 for i in range(500_000)]
snap = tracemalloc.take_snapshot()
for stat in snap.statistics("traceback")[:3]:
print(stat)
for line in stat.traceback.format():
print(" ", line)Finding Memory Leaks
Take two snapshots around a suspected leak and compare. Growing stats between snapshots indicate a leak.
import tracemalloc
tracemalloc.start()
snap_before = tracemalloc.take_snapshot()
for _ in range(100):
suspected_leaky_function()
snap_after = tracemalloc.take_snapshot()
diff = snap_after.compare_to(snap_before, "lineno")
for stat in diff[:5]:
print(stat)get_traced_memory()
tracemalloc.get_traced_memory() returns (current, peak) bytes — useful for lightweight before/after checks.
import tracemalloc
tracemalloc.start()
before, _ = tracemalloc.get_traced_memory()
do_something()
after, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"Delta: {(after-before)/1024:.1f} KB, Peak: {peak/1024:.1f} KB")memory_profiler
memory_profiler provides line-by-line memory usage, similar to line_profiler for CPU.
# pip install memory_profiler
from memory_profiler import profile
@profile
def build_data():
data = [i**2 for i in range(100_000)]
filtered = [x for x in data if x % 2 == 0]
return filtered
build_data()
# python -m memory_profiler script.pymemray
memray (by Bloomberg) is a fast Python memory profiler with flamegraph output.
# pip install memray
# python -m memray run script.py
# python -m memray flamegraph memray-script.py.bin
# Generates an interactive HTML flamegraph
# showing allocations by call stackReducing Memory Usage
Common techniques: use generators instead of lists, __slots__, array module for numeric data, numpy arrays, and avoid keeping large objects alive in closures.
# Instead of:
data = [process(x) for x in huge_list] # all in memory
# Use a generator:
def gen_data(lst):
for x in lst:
yield process(x)
for item in gen_data(huge_list):
consume(item) # one at a timesys.getsizeof()
sys.getsizeof(obj) returns the memory used by an object in bytes (shallow — does not include referenced objects).
import sys
print(sys.getsizeof([])) # 56
print(sys.getsizeof([1,2,3])) # 88
print(sys.getsizeof("hello")) # 54
print(sys.getsizeof({})) # 64
# For deep size, use recursive measurement:
def deep_size(obj):
return sys.getsizeof(obj) + sum(
sys.getsizeof(v) for v in vars(obj).values()
if hasattr(obj, "__dict__")
)Profiling in Production
Run tracemalloc with limited nframes in production to minimise overhead. Store snapshots to a file for offline analysis.
import tracemalloc, pickle
tracemalloc.start(nframe=5) # low overhead
# ... serve some requests ...
snap = tracemalloc.take_snapshot()
with open("snap.pkl","wb") as f:
pickle.dump(snap, f)
# Analyse later offlineQuick Check
What do the two values returned by tracemalloc.get_traced_memory() represent?
Recap
Use tracemalloc.start() + snapshots to find memory leaks. Compare snapshots with compare_to(). Use memory_profiler for line-by-line usage and memray for flamegraphs. Reduce memory with generators, __slots__, and NumPy arrays.
Frequently asked questions
Is the “Memory Profiling with tracemalloc” lesson free?
Yes — the full text of “Memory Profiling with tracemalloc” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Memory Profiling with tracemalloc”?
Track memory allocations and find leaks with tracemalloc. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Memory Profiling with tracemalloc” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- CPython Reference Counting
- The Garbage Collector and Cyclic References
- Profiling with cProfile and line_profiler
- Memory Profiling with tracemalloc