python内存泄漏解决方案_Python-解决内存泄漏

1586010002-jmsa.png

I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the other threads on memory leaks). Due to time constraints, I have had to give up on finding the leak, but if I were able to isolate each experiment, the program would probably run long enough to produce the results I need.

Would running each test in a separate thread help?

Are there any other methods of isolating the effects of a leak?

Detail on the specific situation

My code has two parts: an experiment runner and the actual experiment code.

Although no globals are shared between the code for running all the experiments and the code used by each experiment, some classes/functions are necessarily shared.

The experiment runner isn't just a simple for loop that can be easily put into a shell script. It first decides on the tests which need to be run given the configuration parameters, then runs the tests then outputs the data in a particular way.

I tried manually calling the garbage collector in case the issue was simply that garbage collection wasn't being run, but this did not work

Update

Gnibbler's answer has actually allowed me to find out that my ClosenessCalculation objects which store all of the data used during each calculation are not being killed off. I then used that to manually delete some links which seems to have fixed the memory issues.

解决方案

You can use something like this to help track down memory leaks

>>> from collections import defaultdict

>>> from gc import get_objects

>>> before = defaultdict(int)

>>> after = defaultdict(int)

>>> for i in get_objects():

... before[type(i)] += 1

...

now suppose the tests leaks some memory

>>> leaked_things = [[x] for x in range(10)]

>>> for i in get_objects():

... after[type(i)] += 1

...

>>> print [(k, after[k] - before[k]) for k in after if after[k] - before[k]]

[(, 11)]

11 because we have leaked one list containing 10 more lists

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值