1.通过两次快照对
import tracemalloc # 这个是python自带的 def on_start(): ''' 需要测试的代码 ''' pass tracemalloc.start() snapshot1 = tracemalloc.take_snapshot() on_start() # 需要测试的代码 snapshot2 = tracemalloc.take_snapshot() top_stats = snapshot2.compare_to(snapshot1, 'lineno') print("[ Top 10 differences ]") for stat in top_stats[:30]: # 打印出来内存增加最多的前三十个代码地址。 print(stat)
2.显示最大内存块的回溯的代码
import tracemalloc # 这个是python自带的 def on_start(): ''' 需要测试的代码 ''' pass tracemalloc.start(25) on_start() # 需要测试的代码 snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('traceback') # pick the biggest memory block stat = top_stats[0] print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024)) for line in stat.traceback.format(): print(line)
标签:stat,stats,python,top,tracemalloc,start,snapshot,内存 From: https://www.cnblogs.com/yoyo1216/p/17828985.html