Objective

Build a script to analyze memory usage of Python programs.

Tools & Technologies

  • Python 3
  • psutil
  • tracemalloc
  • sys

Key Commands

tracemalloc.start()
psutil.Process().memory_info().rss
sys.getsizeof(obj)
gc.get_objects()

Lab Steps

01
tracemalloc

Use tracemalloc to trace memory allocations and find leaks.

02
psutil Process Memory

Monitor process RSS and VMS memory usage.

03
Object Size

Measure object sizes with sys.getsizeof and objgraph.

04
Profiling

Run memory profiling on a script and identify hotspots.

Challenges Encountered

  • sys.getsizeof doesn't account for referenced objects
  • tracemalloc overhead affects performance

Key Takeaways

  • Memory leaks in long-running scripts are often from growing caches
  • Use gc.collect() to force garbage collection during debugging