python 内存泄漏查找方法

方法

import tracemalloc

def test():
	tracemalloc.start()
	snapshot1 = tracemalloc.take_snapshot()
	## 你的各种数据操作
	………………
	snapshot2 = tracemalloc.take_snapshot()
    top_stats = snapshot2.compare_to(snapshot1, 'lineno')
    print(top_stats[0:10])

打印结果:

[<StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/json/decoder.py' lineno=355>,)> size=10123317 (+9533677) count=304448 (+297771)>, 
<StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/re.py' lineno=191>,)> size=44658 (+44658) count=387 (+387)>,
<StatisticDiff traceback=<Traceback (<Frame filename='/Users/PycharmProjects/algo-question/src/main.py' lineno=87>,)> size=25024 (+22784) count=391 (+356)>,
 <StatisticDiff traceback=<Traceback (<Frame filename='/Users/PycharmProjects/algo-question/src/main.py' lineno=90>,)> size=3240 (+3240) count=1 (+1)>, 
 <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/site-packages/sklearn/svm/_base.py' lineno=616>,)> size=3176 (+3176) count=2 (+2)>,
  <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/site-packages/pandas/core/indexes/base.py' lineno=409>,)> size=3840 (+1920) count=6 (+3)>,
   <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/site-packages/requests/utils.py' lineno=313>,)> size=2424 (+1344) count=26 (+21)>, 
   <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/http/client.py' lineno=1209>,)> size=1344 (+1344) count=21 (+21)>, 
   <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/site-packages/requests/structures.py' lineno=46>,)> size=1928 (+1200) count=13 (+10)>, 
 <StatisticDiff traceback=<Traceback (<Frame filename='/Users/opt/anaconda3/envs/python36/lib/python3.6/threading.py' lineno=237>,)> size=2320 (+1056) count=6 (+2)>]

结果显示的是你一次调用后,内存新增情况,比如:size=3176 (+3176)
就代表内存为3176,比上次新增3176,说明初始内存为0;
size=2424 (+1344) 表示初始内存 为1080, 内存有残留,当然最终要多运行几次来查看内存情况。

其他方法:

显示变量引用次数

print('sentences:{}'.format(sys.getrefcount(sentences)))

保存各个类型内存增长情况:

with open('log_del.txt', 'a+') as f:
        objgraph.show_most_common_types(limit=50, file=f)
        f.close()

打印内存增长情况:

objgraph.show_growth()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柒然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值