python - 就地释放 Numpy 内存

标签 python numpy memory-management

有没有办法让 numpy 释放数组使用的内存?我不能只运行 del array,因为该数组在别处被引用。

为什么这很重要以及为什么我认为这是安全的示例:

def run():
   arr = np.array(....)
   arr2 = process(arr)
   fit(arr2)

我可以编辑 process 但不能 run。现在 arr 拥有大量在 process 运行后不再需要的内存。创建 arr2 后,我想从 process 中删除 arr 的内容。

最佳答案

您可以尝试将数组调整为一个小数组:

arr.resize((2,), refcheck=False)

它就地改变数组:

a.resize(new_shape, refcheck=True)

Change shape and size of array in-place.

...

Notes

This reallocates space for the data area if necessary.

Only contiguous arrays (data elements consecutive in memory) can be resized.

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.

关于python - 就地释放 Numpy 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36160123/

相关文章:

Python快速散列可变对象

python - 使用 numpy 的批量张量乘法

objective-c - Objective-C : App Crashes when setting up connection (during refresh)

python - 在 Google 云存储桶中使用 PIL 更改图像大小(从 GCloud 中的虚拟机)

python - Airflow 无法导入自定义 python 包

python - 使用 Scipy 拟合 Weibull 分布

python - 将数组写入文本文件

c++ - 如何显式管理异构类型(和大小)的多个池分配器?

C malloc + free 不断增加内存占用

python - 如何在 Qt Widget 中设置文本格式