我有一个使用大量 dict
对象的 Python2.7 应用程序,其中大多数包含字符串作为键和值。
有时这些字典和字符串不再需要,我想从内存中删除它们。
我尝试了不同的方法,例如 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()
。 - muddyfish