Memray: A Memory Profiler for Python Applications
Memray is a powerful and accurate memory profiler for Python applications, offering detailed insights into memory allocations, identifying leaks, and visualizing memory usage over time. It leverages low-level operating system features to accurately track memory, including native calls, and provides various output formats like flame graphs and interactive textual user interfaces. Currently at version 1.19.2, Memray is actively maintained with a consistent release cadence, frequently delivering bug fixes, performance enhancements, and support for newer Python features and operating system environments.
Warnings
- gotcha Memray relies on C extensions and can utilize system debug symbols (e.g., `elfutils` on Linux) for native stack traces. This might require C compilers (`gcc`, `clang`) and Python development headers (`python3-dev`) if pre-built wheels are unavailable or for certain advanced features. Past versions have also addressed platform-specific issues like infinite loops on ARM Linux.
- gotcha While designed for low overhead, `memray` is a profiler and introduces some performance impact and memory usage to the profiled application. The overhead can vary significantly based on the application's allocation patterns and the system it's running on.
- breaking The `memray` Textual User Interface (TUI) reporter has specific compatibility requirements with the `textual` library. `memray` v1.16.0 added support for Textual 2.0, and v1.17.0 for Textual 3.x. Using an incompatible `textual` version with `memray` might lead to runtime errors or incorrect display.
- gotcha Memray primarily tracks memory *allocations* and deallocations, not necessarily the *live memory* held by objects that have already been allocated. This distinction is crucial for interpreting reports: a high allocation count doesn't always mean a memory leak if objects are properly deallocated.
- gotcha Older `memray` versions might not provide complete or accurate native stack traces for Python 3.14+ due to changes in its tail call interpreter. Version 1.19.2 specifically added support for this.
Install
-
pip install memray
Imports
- Tracker
from memray import Tracker
Quickstart
import memray
import os
def allocate_some_memory():
return [0] * 1024 * 1024 # Allocate 8MB
if __name__ == "__main__":
output_file = "memray_output.bin"
with memray.Tracker(output_file):
my_data = allocate_some_memory()
print(f"Memory profile saved to {output_file}")
# To generate a flame graph, run from your shell:
# memray flamegraph memray_output.bin
# To programmatically create a report:
# from memray import Metadata, MemrayFile
# with MemrayFile(output_file) as f:
# metadata = Metadata.parse_file(f)
# print(f"Total allocations: {len(f.iter_records())}")