Pympler
Pympler is a development tool designed to measure, monitor, and analyze the memory behavior of Python objects in a running application. It provides detailed insights into the size and lifetime of Python objects, aiding in the identification of memory bloat, leaks, and other undesirable runtime behaviors. The current stable version is 1.1.
Warnings
- breaking Pympler dropped support for Python 2.7 and Python 3.5 starting with version 1.0. Older Python versions require Pympler < 1.0.
- gotcha Repeated calls to `muppy.get_objects()` in a tight loop can themselves consume significant memory, potentially masking or exacerbating actual memory leak issues. The `get_objects()` function collects references to all live Python objects.
- gotcha The `asizeof` module's accuracy can be affected by internal CPython object layout changes in newer Python versions, potentially leading to discrepancies in reported sizes for certain object types.
- gotcha Pympler operations, particularly those that traverse the entire object graph (e.g., `muppy.get_objects()`, `asizeof.asizeof()` on complex objects), can be computationally intensive and may introduce a noticeable performance overhead in performance-critical applications.
Install
-
pip install Pympler
Imports
- asizeof
from pympler import asizeof
- muppy
from pympler import muppy
- summary
from pympler import summary
- tracker
from pympler import tracker
Quickstart
from pympler import asizeof, muppy, summary
class MyObject:
def __init__(self, data):
self.data = data
self.large_list = [0] * 1000 # A list consuming some memory
# 1. Measure the size of an individual object recursively
obj = MyObject('some string data')
print(f"Size of obj: {asizeof.asizeof(obj)} bytes")
# 2. Get a summary of all objects in memory
all_objects_before = muppy.get_objects()
sum1 = summary.summarize(all_objects_before)
print("\n--- Memory Summary (Before) ---")
summary.print_(sum1, limit=5) # Print top 5 largest object types
# Create more objects
my_list = [MyObject(f'data_{i}') for i in range(10)]
# 3. Get a diff in memory usage
all_objects_after = muppy.get_objects()
sum2 = summary.summarize(all_objects_after)
print("\n--- Memory Summary (After, diff) ---")
diff = summary.diff(sum1, sum2)
summary.print_(diff, limit=5) # Print top 5 changes
# Example of tracker for change over time (simplified)
tr = tracker.SummaryTracker()
# Perform some operations that might create new objects
def create_temp_objects():
local_list = ["temp_str"] * 500
create_temp_objects()
print("\n--- Tracker Diff after create_temp_objects() ---")
tr.print_diff(limit=5)