我有一个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
我希望在这里“收集”一些对象并释放一些内存。
我做错了什么吗?任何其他方法来删除未使用的对象或至少找到意外使用对象的位置。
如果你创建了一个大对象并再次删除它,Python可能已经释放了 内存,但涉及的内存分配器不一定返回 操作系统的内存,因此 Python 进程可能看起来使用了 虚拟内存比实际使用的多得多。
唯一真正可靠的方法来确保大量但 内存的临时使用在完成后会将所有资源返回给系统, 是在子进程中进行这种使用,该子进程会执行消耗内存的工作 然后终止。
因此,您可以使用
multiprocessing
生成子进程,执行内存占用计算,然后确保子进程终止时释放内存:
import multiprocessing as mp
import resource
def mem():
print('Memory usage : % 2.2f MB' % round(
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0,1)
)
mem()
def memoryhog():
print('...creating list of dicts...')
n = 10**5
l = []
for i in xrange(n):
a = 1000*'a'
b = 1000*'b'
l.append({ 'a' : a, 'b' : b })
mem()
proc = mp.Process(target=memoryhog)
proc.start()
proc.join()
mem()
产量
Memory usage : 5.80 MB
...creating list of dicts...
Memory usage : 234.20 MB
Memory usage : 5.90 MB
使用多处理和一个名为 Ray 的库,这可能有点用,该库使用共享内存在进程之间执行多 GB 数据共享。这种方式很容易生成辅助进程,并且仍然可以从父进程快速轻松地访问相同的对象。