python内存监测工具memory_profiler

发布时间 2023-10-24 20:20:40作者: 贝壳里的星海

内存监测工具memory_profiler

memory_profiler是Python的一个第三方库,其功能时基于函数的逐行代码分析工具

memory_profiler 是一个监控进程内存消耗的模块,也可以逐行分析 Python 程序的内存消耗。它是一个依赖 psutil 模块的纯 Python 模块。

安装

pip install -U memory_profiler

参数注解

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()
Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

部分参数注解:

Mem usage:执行完改行代码后内存的使用情况。
Increment:执行完该行代码,内存增加了多少。
Occurrences:该行被命中多少次。
Line #:代码所在行号。
Line Contents:该行代码的内容。

简单使用

三种使用方式中,前两种是针对逐行的内存使用分析,另外一种针对时间维度的内存使用分析。

使用装饰器,设置显示精度

from memory_profiler import profile

@profile(precision=5)
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    python/test.py
# python  python/test.py
Line #    Mem usage    Increment  Occurrences   Line Contents
=============================================================
     6  27.88672 MiB  27.88672 MiB           1   @profile(precision=5)
     7                                         def my_func():
     8  35.51953 MiB   7.63281 MiB           1       a = [1] * (10 ** 6)
     9 188.10938 MiB 152.58984 MiB           1       b = [2] * (2 * 10 ** 7)
    10  35.51953 MiB -152.58984 MiB           1       del b
    11  35.51953 MiB   0.00000 MiB           1       return a

输出在日志中

# _*_coding:utf-8_*_
# Python程序内存分析
from memory_profiler import profile
 
 
# 使用装饰器,配置精度,将结果输出到日志
@profile(precision=4, stream=open("memory_profiler.log", "w+"))
def my_func():
    import time
    a = [1, 3, 4, 5]
    for i in a:
        pass
    return time.time()
 
 
if __name__ == '__main__':
    my_func()

mprof 使用

时间维度内存分析

使用 mprof 执行程序在时间维度分析进程的内存使用情况。下面介绍了一共有四种情况,分别是:单进程,多进程,记录子进程内存占用,多进程并记录子进程内存占用。

mprof run:运行可执行文件,记录内存使用情况
mprof plot:绘制一个记录的内存使用情况(默认情况下,最后一个)
mprof list:以用户友好的方式列出所有记录的内存使用情况文件。
mprof clean:删除所有记录的内存使用情况文件。
mprof rm:删除特定记录的内存使用情况文件
mprof run script.py   # 运行程序,会生成一个结果数据文件
mprof plot			  # 根据最后一条数据文件生成图表
方式一:总结所有子进程的内存和父进程的使用情况并跟踪每个子进程
mprof run --include-children <script>
 
 
 
方式二:独立于主进程跟踪每个子进程,通过索引将子行序列化到输出流。使用多进程
 
mprof run --multiprocess <script> 

内存监测其他工具

https://blog.csdn.net/lanyang123456/article/details/100860904

参考资料

https://zhuanlan.zhihu.com/p/121003986

https://www.cnblogs.com/kaituorensheng/p/5669861.html