【问题标题】:tracemalloc in python 3.4python 3.4中的tracemalloc
【发布时间】:2023-03-03 06:19:27
【问题描述】:

我正在尝试使用 Python 的 tracemalloc 模块并从 API documentation 复制 display_top 函数。输出如下所示,这不是很有帮助:

 #1: collections/__init__.py:366: 85.6 KiB
  exec(class_definition, namespace)

 #2: python3.4/ast.py:55: 83.9 KiB
   return tuple(map(_convert,

我真正想看到的是在我的应用程序中从哪里调用这些函数。所以,我真的很想看到最旧的帧而不是最近的帧。这甚至是正确的方法吗?

我尝试过tracemalloc.start(25),这样它最多可以存储 25 帧。 但是如果我检查len(stat.traceback),它是1!所以,我只能打印最近的帧,这没什么用。

def display_top(self, snapshot, group_by="lineno",  limit=_NUM_MEMORY_BLOCKS):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(group_by)

    for index, stat in enumerate(top_stats[:limit], 1):
        # Ideally, I want to print all frames in traceback. 
        # But length of the traceback is somehow always 1 !!
        frame = stat.traceback[0] 
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        log.debug("#%s: %s:%s: %.1f KiB", index, filename, frame.lineno, stat.size / 1024)
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            log.debug("    %s", line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        log.debug("%s other: %.1f KiB", len(other), size / 1024)
    total = sum(stat.size for stat in top_stats)
    log.debug("Total allocated size: %.1f KiB", total / 1024)

【问题讨论】:

  • 我认为您想查看最新的帧,实际上,还想查看一些较旧的帧,以查看调用分配的位置,就像崩溃时的“正常”堆栈跟踪一样。我和你有完全相同的问题,当我找到解决方案时,我会告诉你。

标签: python python-3.x memory-leaks


【解决方案1】:

调用snapshot.statistics时,需要传递'traceback'而不是'lineno';在那种情况下,tracemalloc.start(25) 确实会存储 25 帧,您可以显示这些帧,例如像这样:print('\n'.join(stat.traceback.format()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多