gpt4 book ai didi

Python 不释放内存

转载 作者:太空狗 更新时间:2023-10-30 00:20:04 25 4
gpt4 key购买 nike

我一直在处理 XML 资源,Python 似乎发出了一种奇怪的行为。我已经测试了 lxml 库和 xml.etree.ElementTree,它们都在应该由 gc 收集后保存内存。我输入了 gc.collect() 作为测试,但没有发生任何其他事情:进程仍持有内存。

导入:

import time
from lxml import etree
import gc

这是代码:

def process_alternative():
"""
This alternative process will use lxml
"""
filename = u"/tmp/randomness.xml"
fd = open(filename, 'r')
tree = etree.parse(fd)
root = tree.getroot()

accum = {}

for _item in root.iter("*"):
for _field in _item.iter("*"):
if _field.tag in accum.keys():
accum[_field.tag] += 1
else:
accum[_field.tag] = 1

for key in accum.keys():
print "%s -> %i" % (key, accum[key])

fd.close()
gc.collect()

这是我的主要内容

if __name__ == "__main__":
while True:
print "Wake up!"
process_alternative()
print "Sleeping..."
time.sleep(30)

如你所见,这个主要调用“process_alternative”,然后休眠。 XML文件提供加载内存近800MB;因此,在 time.sleep 之前,进程应该释放内存,返回到所需的基本 VM 内存(大约 32MB?)。相反,进程继续持有大约 800MB。

关于为什么每次迭代后内存都没有被释放的任何提示?

使用 ubuntu 13.04,Python 2.7.4

这个函数在每次迭代中释放内存

def check_memory():
ac1 = [a1**5 for a1 in xrange(10000000)]
time.sleep(5)
ac2 = [a1**5 for a1 in xrange(10000000)]
time.sleep(5)
ac3 = [a1**5 for a1 in xrange(10000000)]

最佳答案

我不知道为什么,但即使我设置了对 gc.collect() 的显式调用,进程仍保留内存。

经过一些尝试,感谢 Martijn Pieters,出现了一个解决方案。呼唤

len(gc.get_objects())

释放所有访问的内存,并在不忙时让进程保持在正确的资源上。奇怪,但真实。

关于Python 不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20489585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com