如何显式释放 numpy 数组内存?

问题描述 投票:0回答:1

如何显式释放与

numpy
数组关联的内存?

像往常一样,Stackexchange 上有很多标题大致相同的问题,但没有正确答案。

这是问题的一个例子:

import numpy as np

big_arr = ...
def process_big_arr(arr: np.ndarray) -> np.ndarray:
  big_intermediate_arr_1 = ... # some function of `arr`.
  del arr # This will not trigger garbage collection because a reference to `big_arr` still exists in the outer scope.
  big_intermediate_arr_2 = ... # Memory error here, because I'm out of RAM. I want the input array `arr` to be destroyed. I won't be using it again.
  big_output_arr = ...
  return big_output_arr
output = process_big_arr(big_arr)

我在

numpy
文档中找不到一个以释放内存的方式对数组进行 mutates 的函数。

有什么办法可以做到这一点吗?也许通过编辑 numpy 数组的属性并更改其内存指针或其他什么?

python numpy memory-management
1个回答
0
投票

我还没有亲自测试过这一点,但根据其他来源,将数组设置为

None
会将引用计数设置为0,从而使垃圾收集器释放数组。

arr = None
© www.soinside.com 2019 - 2024. All rights reserved.