mprofile: A Low-Overhead Memory Profiler

0.0.15 · active · verified Thu Apr 16

mprofile is a low-overhead sampling memory profiler for Python, derived from heapprof, with an interface similar to tracemalloc. It attempts to give results comparable to tracemalloc, but uses statistical sampling to lower memory and CPU overhead. The sampling algorithm is the one used by tcmalloc and Golang heap profilers. The current version is 0.0.15, and it is compatible with Python >= 3.4.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `mprofile`, simulate some memory allocation, take a snapshot of the current memory usage, and print the top memory-consuming lines. The `sample_rate` is set to the recommended 128KB for a balance between overhead and precision.

import mprofile
import os

# Start profiling with a recommended sample rate (128KB) for low overhead
mprofile.start(sample_rate=128 * 1024)

# Simulate some memory allocation
data = []
for i in range(100_000):
    data.append(os.urandom(100)) # Allocate 100 bytes per iteration

# Take a snapshot of memory usage
snapshot = mprofile.take_snapshot()

# Print top 5 memory consuming lines and their statistics
print("Top 5 memory consuming lines:")
for stat in snapshot.statistics(key_type='lineno')[:5]:
    print(stat)

# Stop profiling
mprofile.stop()

view raw JSON →