Python 3.4中的tracemalloc

7
我正在尝试使用Python的tracemalloc模块,并从API文档中复制了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)

2
我认为你想要查看最新的帧以及一些旧的帧,以便了解分配是从哪里调用的,就像从崩溃中的“正常”堆栈跟踪一样。我和你有完全相同的问题,如果我找到解决方案,我会告诉你。 - Ytsen de Boer
1个回答

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接