我試圖在一個tracemalloc用于提取代碼幀的大型專案中找出記憶體泄漏。但是,我無法獲得超過一個最深的框架,這對于具有大量依賴項和無數嵌套呼叫的大型專案來說毫無用處。根據檔案,我嘗試使用:
tracemalloc.start極限論證PYTHONTRACEMALLOC環境變數-X tracemalloc命令列引數
并且tracemalloc.get_traceback_limit()顯示了我設定的正確數字。但是,每個 Traceback 物件仍然只有一幀。它在不同機器上的 Python 版本 3.8.5 和 3.9.7 上的作業方式相同。這里有什么問題??我怎樣才能解決這個問題?
這是最小的例子:
import os
import tracemalloc
def get_top_malloc(trace_number):
snapshot = tracemalloc.take_snapshot()
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics("lineno")
msg = []
if trace_number > 0:
msg.append(f"Top malloc {trace_number} lines")
for index, stat in enumerate(top_stats[:trace_number]):
msg.append(f"#{index}: {stat.size // 1024} KB, {stat.count} times")
print(stat.traceback._frames) # Only single frame is here!
print(dir(stat.traceback))
msg.extend(line for line in stat.traceback.format(limit=16))
other = top_stats[trace_number:]
if other:
size = sum(stat.size for stat in other)
msg.append(f"{len(other)} other: {size // 1024} KB")
total = sum(stat.size for stat in top_stats)
msg.append(f"Total allocated size: {total // 1024 // 1024} MB")
return "\n".join(msg)
storage = {}
def func2():
def func3():
value = '3.1415926535897932384626433832795028841971'
value = value * 4096
storage['pi'] = value
func3()
def func1():
func2()
if __name__ == "__main__":
tracemalloc.start(4)
print(f"\n-- Limit: {tracemalloc.get_traceback_limit()}")
func1()
print(f"\n-- {get_top_malloc(1)}")
tracemalloc.stop()
uj5u.com熱心網友回復:
我找到了解決方案,它是微不足道的,但并不明顯。statistics(...)快照物件的方法采用一個key_type引數,用于按檔案 ( "filename")、檔案 行 ( "lineno") 或整個回溯 ( "traceback")對跟蹤進行分組。我使用了默認值"lineno",它過濾掉了每個回溯的最后一幀之外的所有內容,因此切換到該"traceback"選項解決了問題并允許我獲得我需要的所有幀:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/378587.html
標籤:Python 蟒蛇-3.x 调试 内存泄漏 malloc
