我用 python 2.7.7 运行了以下命令:
import gc
import memory_profiler
print memory_profiler.memory_usage()[0]
x = [i for i in range(10000000)]
print memory_profiler.memory_usage()[0]
x = None
print memory_profiler.memory_usage()[0]
gc.collect()
print memory_profiler.memory_usage()[0]
它产生了以下输出:
11.36328125
321.9140625
245.6171875
245.6171875
这是怎么回事?内存使用量减少约 25% 的原因是什么?
最佳答案
这post应该给你一个很好的主意。基本上,python 将有一些空闲列表内存,当它们用完时,内存就会成为开销。例如:
import gc
import memory_profiler
print memory_profiler.memory_usage()[0]
x = [i for i in range(10000)]
print memory_profiler.memory_usage()[0]
x = None
print memory_profiler.memory_usage()[0]
gc.collect()
print memory_profiler.memory_usage()[0]
输出:
7.28515625
7.796875
7.796875
7.796875
但是当我用一个非常大的列表运行你的代码时,结果是不同的,代码:
import gc
import memory_profiler
print memory_profiler.memory_usage()[0]
x = [i for i in range(10000000)]
print memory_profiler.memory_usage()[0]
x = None
print memory_profiler.memory_usage()[0]
gc.collect()
print memory_profiler.memory_usage()[0]
输出:
7.3515625
387.31640625
311.30859375
94.7890625
所以如果我说的一切都是真的,如果它真的在吃完空闲的 python 列表内存后造成开销;让我们尝试释放类似于 post 的内存:
import gc
import memory_profiler
def release_list(a):
del a[:]
del a
print memory_profiler.memory_usage()[0]
x = [i for i in range(10000000)]
release_list(x)
print memory_profiler.memory_usage()[0]
x = None
print memory_profiler.memory_usage()[0]
gc.collect()
print memory_profiler.memory_usage()[0]
输出:
7.34765625
318.3359375
318.3359375
96.3359375
显然,当您分配 x = None 时,它释放了您使用非常大的列表启动的额外负担。通常在现实世界中,python 空闲列表内存应该可以满足用户的要求,并且不会有任何区别。
其他资源:
关于python 实验 gc 和 memory_profiler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37075939/