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')
for i in range(30, 0, -1):
    stat = top_stats[i]
    print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
    for line in stat.traceback.format():
        print(line)
    print("*" * 100)
    print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))