我正在寻找从大型Python代码库生成函数运行过程中堆使用情况或内存分配的摘要。

我对heapy很熟悉,在我的代码中的特定点上对堆进行“快照”非常有用,但是我发现很难用它生成“随时间变化的存储器”摘要。我也玩过line_profiler,但是它在运行时有效,而不是内存。

现在我的后备是Valgrind和massif,但是缺少Heapy和line_profiler给出的很多上下文Python信息。后两者是否有某种组合,可以在Python程序的执行范围内提供内存使用或堆增长的感觉?

最佳答案

我将在程序启动时使用 sys.settrace 注册自定义跟踪器功能。对于每一行代码,都会调用custom_trace_function。然后,您可以使用该功能将堆或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)

10-06 06:34
查看更多