介绍
本文介绍memory_profiler,是一款第三方平台控制模块,可以监控进程的运行内存消耗以及python程序流程的运行内存消耗。它是一个纯python模块,依赖于psutil控制模块。

操作方法
您可以使用以下两种方法来查询程序执行的内存占用情况:
- 使用装饰器运作方式
- 使用cmd运作方式
使用以下代码装饰您的函数:
@profile
def func1():
s1 = [i for i in range(loop)]
s2 = []
for i in range(loop):
if i & 1 == 1:
s2.append(i)
result = sum(s1) + sum(s2)
del s1
del s2
return result
您可以运行以下命令:
python -m memory_profiler test_code.py
其中,test_code.py是您的程序文件名。
填补
本文还提供了以下两种应用实例:
- 打印内存使用结论到终端设备
- 导出到文件并保留小数位
@profile
def test1():
c = list()
for item in range(10000):
c.append(item)
if __name__ == '__main__':
test1()
运行后可以得到以下结论:
| Filename | Line# | Mem usage Increment | Line Contents |
|---|---|---|---|
| D:/python/test_sip/test_check_es.py | 474 | 16.6MiB | @profile |
| 475 | def test1(): |
||
| 476 | 0.0MiB | c = list() |
|
| 477 | 0.0MiB | for item in range(10000): |
|
| 478 | 0.1MiB | c.append(item) |
@profile(precision=4, stream=open('memory_profiler.log', 'w+'))
def test1():
c = list()
for item in range(10000):
c.append(item)
if __name__ == '__main__':
test1()
运行后,得到的结论将被导出到名为memory_profiler.log的文件中,且会保留小数点后四位。
以上是本文的内容,希望对您有帮助!
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/6653.html
