Python的内存检测工具:Memory Profiler
jopen
10年前
简介
memory_profiler用于监视进程的内存消耗,以及基于行的内存消耗的分析。这是一个纯Python模块,依赖psutil,尤其是在Windows下。
快速入门
example.py:
@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 Filename: example.py Line # Mem usage Increment Line Contents ================================================ 1 10.539 MiB 0.000 MiB @profile 2 def my_func(): 3 18.172 MiB 7.633 MiB a = [1] * (10 ** 6) 4 170.762 MiB 152.590 MiB b = [2] * (2 * 10 ** 7) 5 18.172 MiB -152.590 MiB del b 6 18.172 MiB 0.000 MiB return a
模块的方式
example.py:
@profile def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a if __name__ == '__main__': my_func()
执行结果:
#python example.py Filename: example.py Line # Mem usage Increment Line Contents ================================================ 3 9.7 MiB 0.0 MiB @profile 4 def my_func(): 5 17.4 MiB 7.6 MiB a = [1] * (10 ** 6) 6 170.0 MiB 152.6 MiB b = [2] * (2 * 10 ** 7) 7 17.4 MiB -152.6 MiB del b 8 17.4 MiB 0.0 MiB return a
还可以指定精度:
from memory_profiler import profile @profile(precision=4) def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a
-m memory_profiler的调用,精度不会生效。