Memory Profiler
memory-profiler is a Python module designed for monitoring the memory consumption of a Python process, including detailed line-by-line analysis of memory usage within Python programs. It is built purely in Python and depends on the `psutil` module. The current version is 0.61.0. As of the latest information, the package is no longer actively maintained by its original developers.
Warnings
- deprecated The `memory-profiler` package is no longer actively maintained by its original developers. While functional, new features or active issue resolution are unlikely.
- gotcha When using the `mprof run` command-line utility for time-based memory usage with timestamps, importing `@profile` directly in your Python script (`from memory_profiler import profile`) will prevent timestamps from being recorded.
- gotcha Using `memory-profiler` introduces overhead and consumes additional memory itself. It is not recommended for production environments due to its intrusive nature.
- gotcha By default, `memory-profiler` only tracks the memory usage of the parent process. Memory consumed by forked child processes (e.g., when using `multiprocessing`) is not automatically included in the report.
- gotcha Applying the `@profile` decorator can sometimes subtly change the behavior of the decorated function, particularly when interacting with complex data structures or libraries like Pandas, potentially leading to unexpected errors or different outputs than when run un-profiled.
Install
-
pip install -U memory-profiler
Imports
- profile
from memory_profiler import profile
- memory_usage
from memory_profiler import memory_usage
Quickstart
import time
from memory_profiler import profile
# Save this as 'my_script.py'
@profile
def create_large_lists():
a = [0] * (10 ** 6) # Allocates ~8MB
time.sleep(0.1)
b = [1] * (2 * 10 ** 7) # Allocates ~160MB
time.sleep(0.1)
c = [2] * (5 * 10 ** 6) # Allocates ~40MB
del b # Frees ~160MB
return a, c
if __name__ == '__main__':
print("Starting memory intensive task...")
lists = create_large_lists()
print("Task completed.")
# The profiling output will be printed to stdout when run via python -m memory_profiler