2020年11月6日 / 613次阅读 / Last Modified 2020年11月6日
memory_profiler是一个第三方模块,用来测量python进程的内存使用情况。
memory_profiler 是一个监控进程内存消耗的模块,可以逐行分析 Python 程序的内存消耗。它是一个依赖 psutil 模块的纯 Python 模块。
是需要在目标函数上加个装饰器 @profile,就可以实现对此函数内存使用的统计:
$ cat read2.py
import mmap
import os
from functools import partial
def read_file(filename, block_size=mmap.PAGESIZE*1024*256):
filesize = os.path.getsize(filename)
with open(filename, 'rb+') as f:
i = 0
readlen = 0
while True:
length = block_size if filesize-readlen>block_size else filesize-readlen
mm = mmap.mmap(f.fileno(), length, offset=readlen)
cont = mm.read()
mm.close()
yield cont
readlen += len(cont)
if readlen == filesize:
break
i += 1
@profile
def do():
length = 0
for cont in read_file('bigfile'):
length += len(cont)
print(length)
do()
这是一个尝试用mmap来读取大文件的测试,bigfile有1.6G。(这个测试是失败的,使用mmap并没有提高读取超大文件的速度,也没有使用更少的内存,直接使用文件对象的read(N)反而更快更好)
$ python3 -m memory_profiler read2.py
1677721600
Filename: read2.py
Line # Mem usage Increment Occurences Line Contents
============================================================
23 18.426 MiB 18.426 MiB 1 @profile
24 def do():
25 18.426 MiB 0.000 MiB 1 length = 0
26 1042.613 MiB 128.188 MiB 3 for cont in read_file('bigfile'):
27 1042.613 MiB -448.000 MiB 2 length += len(cont)
28
29 594.613 MiB -448.000 MiB 1 print(length)
如果代码执行时间很短,用top等其它工具不一定能够捕获到其内存的情况,用memory_profiler模块就很方便了。
用完后,记得删除 @profile 装饰器!
memory_profiler 还有其它的功能,以后再总结。
-- EOF --
本文链接:https://www.pynote.net/archives/2753
《memory_profiler初体验》有3条留言
前一篇:profile模块的使用
后一篇:如何读超大文件?
©Copyright 麦新杰 Since 2019 Python笔记
注意两个细节:(1)用memory_profiler启动py文件,不需要chmod +x;(2)注意这个--include-children参数:
[ ]这次初次使用memory_profiler模块,发现对于generator是不支持的。 [ ]
安装memory_profiler:
[ ]