Memray: A Memory Profiler for Python Applications

1.19.2 · active · verified Sun Apr 05

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

Install

Imports

Quickstart

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.

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())}")

view raw JSON →