我已经看到两年前发布的一些相关问题,但我想知道最近是否有任何解决方案。
我有一本巨大的字典。我的记忆中大约有 4 个字典(每个 500 MB 大小)。当我继续运行程序时,我需要删除这 4 个字典之一并将内存释放给操作系统。因此,我不可能像之前的一些帖子中提到的那样开始一个新的内存分配子进程。
这里有一些代码来说明这个问题:
import cPickle
import resource
import gc
import time
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "memory usage:", mem
test_dict = {}
for i in range(100000):
test_dict[i] = "AAAAAAAA"
if i%10000 == 0:
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "memory usage:", mem
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "memory usage: (dict created): ", mem
del test_dict
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "mem usage: (dict deleted)", mem
gc.collect()
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "mem usage (garbage collection)", mem
print "sleeping for a few seconds"
time.sleep(30)
gc.collect()
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print "memory usage after sleeping ", mem
这是结果。内存以 KB 为单位报告。
memory usage: 5152
memory usage: 8316
memory usage: 9176
memory usage: 9176
memory usage: 12076
memory usage: 12076
memory usage: 12076
memory usage: 12076
memory usage: 12076
memory usage: 12076
memory usage: 17548
memory usage: (dict created): 17548
mem usage: (dict deleted) 17548
mem usage (garbage collection) 17548
sleeping for a few seconds
memory usage after sleeping 17548
如您所见,内存似乎根本没有释放。我在我的 Ubuntu 11.10 机器上用 Python 2.7.2 试过这个