在尝试为某些 C/C++ 函数微调 Python 绑定中的一些内存泄漏时,我遇到了一些与 Numpy 数组的垃圾收集有关的奇怪行为。
为了更好地解释这种行为,我创建了几个简化的案例。代码是使用 运行的memory_profiler,其输出紧随其后。当涉及到 NumPy 数组时,Python 的垃圾收集似乎没有按预期工作:
# File deallocate_ndarray.py
@profile
def ndarray_deletion():
import numpy as np
from gc import collect
buf = 'abcdefghijklmnopqrstuvwxyz' * 10000
arr = np.frombuffer(buf)
del arr
del buf
collect()
y = [i**2 for i in xrange(10000)]
del y
collect()
if __name__=='__main__':
ndarray_deletion()
Run Code Online (Sandbox Code Playgroud)
使用以下命令,我调用了memory_profiler:
python -m memory_profiler deallocate_ndarray.py
这是我得到的:
Filename: deallocate_ndarray.py
Line # Mem usage Increment Line Contents
================================================
5 10.379 MiB 0.000 MiB @profile
6 def …Run Code Online (Sandbox Code Playgroud) python garbage-collection memory-leaks memory-management memory-profiling