gitmyhub

memory_profiler

Python ★ 4.6k updated 2y ago

Monitor Memory usage of Python code

A Python tool that shows exactly how much memory each line of your code uses. Add a decorator to any function, run it, and get a line-by-line table showing where memory grows or shrinks.

Pythonpsutilmatplotlibsetup: easycomplexity 2/5

memory_profiler is a Python tool for measuring how much memory your Python code uses while it runs. It has two main modes: line-by-line analysis and time-based tracking. The README notes upfront that the package is no longer actively maintained.

The line-by-line mode works by adding a @profile decorator to any Python function you want to inspect. When you run your script with a special command, the tool prints a table showing each line of that function, how much memory the Python process was using after that line ran, and how much memory that line added or freed. This makes it straightforward to spot which specific lines in your code are responsible for large memory increases.

The time-based mode uses a separate command called mprof. You run mprof run followed by your script, and the tool records total memory usage over the full lifetime of the process. Afterward, mprof plot generates a graph of memory over time using matplotlib. If you also decorate functions with @profile, the graph can show exactly when each function was entered and exited, helping identify which part of the program caused a memory spike.

The tool also handles programs that spawn multiple processes. You can tell mprof to track child processes separately or add their memory together with the parent's, giving a more accurate picture of total resource use in parallel workloads.

Installation is a single pip install command. The package depends on psutil, a standard cross-platform library for reading system metrics. It also works inside Jupyter notebooks through a built-in magic command, so you can profile code interactively without leaving the notebook environment.

Where it fits