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.
pip install memrayVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to programmatically use `memray.Tracker` to profile a section of code and save the allocation data to a binary file. The output file can then be analyzed using `memray`'s CLI tools (e.g., `memray flamegraph`) or processed programmatically.
Ensure appropriate build tools and Python development headers are installed. Check `memray`'s GitHub issues for known platform-specific quirks.
Be aware of potential performance implications when using `memray` in performance-critical environments. Profile on representative workloads, but do not expect zero overhead.
If using the TUI, ensure your `textual` dependency is within the supported range for your `memray` version. Consider installing `memray` with the `textual` extra (`pip install memray[textual]`) to automatically manage this dependency.
Understand that `memray` helps identify *where* memory is being allocated. For tracking live object graphs, other tools like `objgraph` or `gc.get_objects()` might be complementary.
Upgrade to `memray` 1.19.2 or newer when profiling applications on Python 3.14 or later to ensure correct native stack trace analysis.
Install memray using pip: `pip install memray`. Ensure the correct Python interpreter is active or explicitly specified when running your application.
To allow attaching to processes owned by the same user, temporarily set `/proc/sys/kernel/yama/ptrace_scope` to `0` (e.g., `echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope`). For containers, ensure the `SYS_PTRACE` capability is explicitly enabled in the container's security context. Alternatively, run the `memray attach` command as the root user.
Ensure that `memray` is installed in the *same* Python environment and for the *exact same* Python version that will be used to run the application. When building container images, install `memray` directly within the final container environment using its target Python version.
Choose either live reporting (`memray run --live-remote my_script.py`) or specify an output file (`memray run -o output.bin my_script.py`), but do not provide both `--live` (or `--live-remote`) and `-o` (or `--output`) in the same command.