Python逐行内存分析器?

Tim*_*Tim 29 python memory profiling

我希望从大型Python代码库中生成函数运行过程中堆使用或内存分配的摘要.

我熟悉heapy,并且在我的代码中的特定点获取堆的"快照"对我很有帮助,但我发现很难用它生成"内存随时间变化"的摘要.我也玩过line_profiler,但这适用于运行时,而不是内存.

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

gur*_*lex 13

我会sys.settrace 在程序启动时使用注册自定义跟踪器功能.将为每行代码调用custom_trace_function.然后,您可以使用该函数将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)
Run Code Online (Sandbox Code Playgroud)


gab*_*ous 5

您可能对memory_profiler感兴趣.