Python逐行内存分析器?
我想从一个大型的Python代码库中,生成一个关于函数运行过程中堆内存使用或内存分配的总结。
我对heapy比较熟悉,它在我代码的特定点上拍摄“快照”时帮了我很多忙,但我发现用它生成“随时间变化的内存”总结有点困难。我也试过line_profiler,但它是用来分析运行时间的,而不是内存。
现在我退而求其次,使用Valgrind和massif,但它缺少了Heapy和line_profiler提供的很多关于Python的上下文信息。有没有什么方法可以把后面这两个工具结合起来,了解Python程序执行过程中内存使用或堆的增长情况呢?
2 个回答
5
你可能会对 memory_profiler 感兴趣。
13
我会在程序启动时使用 sys.settrace
来注册一个自定义的跟踪函数。这个自定义的跟踪函数会在每一行代码执行时被调用。然后,你可以利用这个函数把 heapy 或 meliae 收集到的信息存储到一个文件里,以便后续处理。
下面是一个非常简单的例子,它每秒钟把 hpy.heap() 的输出记录到一个普通的文本文件中:
import sys
import time
import atexit
from guppy import hpy
_last_log_time = time.time()
_logfile = open('logfile.txt', 'w')
def heapy_profile(frame, event, arg):
currtime = time.time()
if currtime - _last_log_time < 1:
return
_last_log_time = currtime
code = frame.f_code
filename = code.co_filename
lineno = code.co_firstlineno
idset = hpy().heap()
logfile.write('%s %s:%s\n%s\n\n' % (currtime, filename, lineno, idset))
logfile.flush()
atexit.register(_logfile.close)
sys.settrace(heapy_profile)