python 3.4中的tracemalloc

sh0*_*731 5 python memory-leaks python-3.x

我正在尝试使用Python的tracemalloc模块。输出如下所示,这不是超级有用。我display_top从这里的api文档复制了函数:https : //docs.python.org/3/library/tracemalloc.html#tracemalloc.Statistic.traceback

 #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,
Run Code Online (Sandbox Code Playgroud)

我真正看到的是这些函数在我的应用程序中的何处被调用。所以,我真的很想看看最旧的框架而不是最新的框架(<---我在这里吗?)

我这样做了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)
Run Code Online (Sandbox Code Playgroud)

Ale*_*kin 0

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