Memray: Python Memory Profiler
Overview
Memray is a powerful memory profiler for Python applications developed by Bloomberg. It provides detailed insights into memory allocation patterns, helps identify memory leaks, and offers various visualization tools to analyze memory usage in Python applications.
Key Features
- Comprehensive Memory Tracking: Tracks all memory allocations in Python applications
- Native Code Support: Profiles both Python and C/C++ extensions
- Multiple Output Formats: Flame graphs, tables, and HTML reports
- Live Monitoring: Real-time memory usage monitoring
- Pytest Integration: Built-in pytest plugin for test memory profiling
- Low Overhead: Minimal performance impact during profiling
- Cross-Platform: Works on Linux, macOS, and Windows
Installation
Basic Installation
# Install via pip
pip install memray
# Install with optional dependencies for better visualization
pip install memray[full]
Development Installation
# Clone the repository
git clone https://github.com/bloomberg/memray.git
cd memray
# Install in development mode
pip install -e .
Basic Usage
1. Command Line Profiling
Simple Script Profiling
# Profile a Python script
memray run my_script.py
# Profile with output file
memray run -o output.bin my_script.py
# Profile a Python module
memray run -m my_module
Advanced Options
# Profile with native code tracking
memray run --native my_script.py
# Profile with live monitoring
memray run --live my_script.py
# Profile with specific output format
memray run --output-format=flamegraph my_script.py
2. Programmatic API Usage
Basic Tracking
import memray
# Track memory allocations in a code block
with memray.Tracker("output.bin"):
# Your code here
data = [i for i in range(1000000)]
result = process_data(data)
Advanced API Usage
import memray
import threading
# Track specific functions
@memray.track_function
def memory_intensive_function():
large_list = [i**2 for i in range(100000)]
return sum(large_list)
# Track memory in threads
def worker_thread():
with memray.Tracker("thread_output.bin"):
# Thread-specific memory tracking
thread_data = process_thread_data()
thread = threading.Thread(target=worker_thread)
thread.start()
Output Formats and Visualization
1. Flame Graph Reports
# Generate flame graph
memray flamegraph output.bin
# Generate flame graph with specific options
memray flamegraph --output=flamegraph.html --temporal output.bin
2. Table Reports
# Generate table report
memray table output.bin
# Generate table with specific sorting
memray table --sort-by=allocations output.bin
3. HTML Reports
# Generate comprehensive HTML report
memray html output.bin
# Generate HTML report with specific options
memray html --output=report.html --temporal output.bin
4. Live Monitoring
# Run with live terminal interface
memray run --live my_script.py
Pytest Integration
Installation
# Install pytest-memray plugin
pip install pytest-memray