使用tracemalloc对python内存进行分析

发布时间 2023-11-13 14:14:53作者: 守护式等待

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)