【问题标题】:Python line-by-line memory profiler?Python逐行内存分析器?
【发布时间】:2026-01-15 00:50:01
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你关心的事情发生在 C 世界,你能用docs.python.org/devguide/gdb.html 做吗?
  • 如果有办法定期自动运行 gdb - 有这样的方法吗?
  • 一个好问题,我很想知道,所以我加了一个赏金。

标签: python memory profiling


【解决方案1】:

我会在程序启动时使用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)

【讨论】:

  • 我还没有尝试过,但看起来我们可能会有赢家。 (我会等到赏金期结束来奖励积分,以防其他人想尝试这个问题)
【解决方案2】:

您可能对memory_profiler 感兴趣。

【讨论】: