Phase 2 of 25 · Topic 2.4

Measuring Memory Layout with sys.getsizeof & tracemalloc

1Concept

`sys.getsizeof()` reports only the direct memory of the container, ignoring the memory of referenced objects. The `tracemalloc` module provides accurate, deep heap allocation profiling, tracking allocations down to specific source code line numbers.

2Architecture Diagram

[ sys.getsizeof(list) ] ---> Reports pointer array ONLY (~88 bytes)
[ tracemalloc ]         ---> Traverses entire heap graph & records RAM footprint

3Code Example

Python 3.12
import tracemalloc

tracemalloc.start()

data = [{"id": i, "data": "x" * 100} for i in range(1000)]

current, peak = tracemalloc.get_traced_memory()
print(f"Current Heap Allocation: {current / 1024:.2f} KB")
print(f"Peak Heap Allocation:    {peak / 1024:.2f} KB")
tracemalloc.stop()

4Expected Output

Current Heap Allocation: 182.45 KB
Peak Heap Allocation:    194.12 KB

5Key Takeaways

  • `sys.getsizeof()` does NOT recursively calculate the size of nested objects.
  • `tracemalloc` is the gold standard for profiling memory leaks in production Python services.
  • Use `tracemalloc.take_snapshot()` to compare memory before and after batch jobs.