memory_profiler是一种监控Python程序运行内存使用情况的模块。

安装

$ pip install -U memory_profiler

使用

使用​​@profile​​装饰器修饰要监控的函数。

from memory_profiler import profile


@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a

if __name__ == '__main__':
my_func()
$ python -m memory_profiler example.py
Line #    Mem usage    Increment  Occurences   Line Contents
============================================================
3 38.816 MiB 38.816 MiB 1 @profile
4 def my_func():
5 46.492 MiB 7.676 MiB 1 a = [1] * (10 ** 6)
6 199.117 MiB 152.625 MiB 1 b = [2] * (2 * 10 ** 7)
7 46.629 MiB -152.488 MiB 1 del b
8 46.629 MiB 0.000 MiB 1 return

参考:
​​​ https://pypi.org/project/memory-profiler/​