【发布时间】:2015-01-16 03:54:01
【问题描述】:
我使用 Python 有一段时间了,有时会遇到一些内存爆炸问题。我已经搜索了一些资源来解决我的问题,例如 Memory profiling embedded python 和 https://mflerackers.wordpress.com/2012/04/12/fixing-and-avoiding-memory-leaks-in-python/ 和 https://docs.python.org/2/reference/datamodel.html#object.del 但是,它们都不适合我。
我目前的问题是使用嵌入式函数时内存爆炸。以下代码可以正常工作:
class A:
def fa:
some operations
get dictionary1
combine dictionary1 to get string1
dictionary1 = None
return *string1*
def fb:
for i in range(0, j):
call self.fa
get dictionary2 by processing *string1*
# dictionary1 and dictionary2 are basically the same.
update *dictionary3* by processing dictionary2
dictionary2 = None
return *dictionary3*
class B:
def ga:
for n in range(0, m):
call A.fb # as one argument is updated dynamically, I have to call it within the loop
processes *dictoinary3*
return something
当我注意到我不需要将 dictionary1 组合到 string1 时,就会出现问题,我可以直接将 dictionary1 传递给 A。 FB。我是这样实现的,然后程序变得非常慢,内存使用量爆炸了10多倍。我已经验证了这两种方法都返回了正确的结果。
有人可以提出为什么这么小的修改会导致如此大的差异吗?
以前,我在对多源树(具有 100,000 多个节点)中的节点进行分级时也注意到了这一点。如果我从源节点(可能具有最大高度)开始进行平整,则内存使用量是从可能具有最小高度的源节点开始的 100 倍。虽然练级时间差不多。
这让我困惑了很长时间。提前非常感谢您!
如果有人感兴趣,我可以通过电子邮件将源代码发送给您,以获得更清晰的解释。
【问题讨论】:
标签: python memory-management memory-leaks