简体   繁体   English

Python逐行内存分析器?

[英]Python line-by-line memory profiler?

I'm looking to generate, from a large Python codebase, a summary of heap usage or memory allocations over the course of a function's run. 我希望从大型Python代码库中生成函数运行过程中堆使用或内存分配的摘要。

I'm familiar with heapy , and it's served me well for taking "snapshots" of the heap at particular points in my code, but I've found it difficult to generate a "memory-over-time" summary with it. 我熟悉heapy ,并且在我的代码中的特定点获取堆的“快照”对我很有帮助 ,但我发现很难用它生成“内存随时间变化”的摘要。 I've also played with line_profiler , but that works with run time, not memory. 我也玩过line_profiler ,但这适用于运行时,而不是内存。

My fallback right now is Valgrind with massif , but that lacks a lot of the contextual Python information that both Heapy and line_profiler give. 我现在的后备是Valgrind with massif ,但是缺少Heapy和line_profiler提供的大量上下文Python信息。 Is there some sort of combination of the latter two that give a sense of memory usage or heap growth over the execution span of a Python program? 是否存在后两者的某种组合,可以在Python程序的执行范围内提供内存使用感或堆增长感?

I would use sys.settrace at program startup to register a custom tracer function. 我会在程序启动时使用sys.settrace来注册自定义跟踪器函数。 The custom_trace_function will be called for each line of code. 将为每行代码调用custom_trace_function。 Then you can use that function to store information gathered by heapy or meliae in a file for later processing. 然后,您可以使用该函数将heapy或meliae收集的信息存储在文件中以供以后处理。

Here is a very simple example which logs the output of hpy.heap() each second to a plain text file: 这是一个非常简单的示例,它将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)

您可能对memory_profiler感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM