6.1. Profiling Mem

6.1.1. Memory Profiler

  • Memory Profiler is a Python module for monitoring memory consumption of a process as well as line-by-line analysis of memory consumption for Python programs.

  • https://github.com/pythonprofilers/memory_profiler

  • https://pypi.org/project/memory-profiler/

  • python -m pip install memory-profiler

  • python -m memory_profiler myfile.py

  • from memory_profiler import profile, memory_usage

  • @profile

  • usage = memory_usage((func, (arg1, arg2), {'kwarg1': 'val'}))

  • python -m mprof run myfile.py

  • python -m mprof plot - requires matplotlib to run

Install:

$ python -m pip install memory-profiler matplotlib

Use Case 1:

Code 6.1. Content of myfile.py
def run():
    [x**x for x in range(0,10_000)]

run()
$ python -m mprof run myfile.py
$ python -m mprof plot
../../_images/profiling-memory-memprof.png

Use Case 2:

Code 6.2. Content of myfile.py
from memory_profiler import profile, memory_usage

@profile
def run():
    [x**x for x in range(0,10_000)]

usage = memory_usage((run, (), {}))
$ python -m memory_profiler myfile.py

6.1.2. References