【发布时间】:2015-11-16 23:54:36
【问题描述】:
我有一个 Python2.7 应用程序,它使用了很多 dict 对象,这些对象主要包含键和值的字符串。
有时不再需要这些字典和字符串,我想将它们从内存中删除。
我尝试了不同的东西,del dict[key]、del dict 等。但应用程序仍然使用相同数量的内存。
下面是一个我希望为内存付费的示例。但它没有:(
import gc
import resource
def mem():
print('Memory usage : % 2.2f MB' % round(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0/1024.0,1)
)
mem()
print('...creating list of dicts...')
n = 10000
l = []
for i in xrange(n):
a = 1000*'a'
b = 1000*'b'
l.append({ 'a' : a, 'b' : b })
mem()
print('...deleting list items...')
for i in xrange(n):
l.pop(0)
mem()
print('GC collected objects : %d' % gc.collect())
mem()
输出:
Memory usage : 4.30 MB
...creating list of dicts...
Memory usage : 36.70 MB
...deleting list items...
Memory usage : 36.70 MB
GC collected objects : 0
Memory usage : 36.70 MB
我希望在这里“收集”一些对象并释放一些内存。
我做错了吗?任何其他删除未使用对象或至少查找意外使用对象的位置的方法。
【问题讨论】:
-
然后做
gc.collect()
标签: python python-2.7 memory memory-management garbage-collection