我正在尝试使用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)