是否将 numpy 数组设置为无空闲内存? [英] Does setting numpy arrays to None free memory?

查看:26
本文介绍了是否将 numpy 数组设置为无空闲内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数百个非常大的矩阵,例如 (600, 800) 或 (3, 600, 800) 形状的矩阵.

I have hundreds of really larges matrices, like (600, 800) or (3, 600, 800) shape'd ones.

因此,一旦我真的不再需要某些东西,我想立即取消分配使用的内存.

Therefore I want to de-allocate the memory used as soon as I don't really need something anymore.

我想:

some_matrix = None

应该完成这项工作,还是只是将引用设置为 None 但在内存中的某个地方仍然分配了空间?(比如保留分配的空间以便将来重新初始化some_matrix)

Should do the job, or is just the reference set to None but somewhere in the Memory the space still allocated? (like preserving the allocated space for some re-initialization of some_matrix in the future)

另外:有时我会切片矩阵,计算一些值并将值放入缓冲区(一个列表,因为它一直被附加).所以将列表设置为 None 肯定会释放内存,对吗?

Additionally: sometimes I am slicing through the matrices, calculated something and put the values into a buffer (a list, because it gets appended all the time). So setting a list to None will definitely free the memory, right?

或者是否存在某种 unset() 方法,其中整个标识符及其引用的对象都被删除"了?

Or does some kind of unset() method exist where whole identifiers plus its referenced objects are "deleted"?

推荐答案

你肯定想看看 垃圾收集.与C/C++这样的编程语言不同,当空间不再需要时,程序员必须自己释放动态分配的内存,python具有垃圾收集功能.意味着python本身在必要时释放内存.

You definitely want to have a look at the garbage collection. Unlike some programming language like C/C++ where the programmer has to free dynamically allocated memory by himself when the space is no longer needed, python has a garbage collection. Meaning that python itself frees the memory when necessary.

当您使用 some_matrix = None 时,您将变量与内存空间断开;引用计数器减少,如果达到0,垃圾收集器将释放内存.当您按照 MSeifert 的建议使用 del some_matrix 时,与答案所说的相反,内存不会立即释放.根据 python 文档,会发生以下情况:

When you use some_matrix = None, you unlink the variable from the memory space; the reference counter is decreased, and if it reaches 0, the garbage collector will free the memory. When you use del some_matrix as suggested by MSeifert, the memory is not freed immediately as opposed to what the answer says. According to python doc, this is what happens:

删除名称会从本地或全局命名空间中删除该名称的绑定

Deletion of a name removes the binding of that name from the local or global namespace

幕后发生的事情是,内存空间的引用计数器减少了 1,而与分配 None 或使用 del 无关.当这个计数器达到0时,垃圾收集器将在以后释放内存空间.唯一的区别是,当使用 del 时,从上下文中可以清楚地看出您不再需要该名称.

What happened under the hood is that the counter of references to the memory space is reduced by 1 independently of assigning None or using del. When this counter reaches 0, the garbage collector will free the memory space in the future. The only difference is that when using del, it is clear from the context that you do not need the name anymore.

如果你查看垃圾收集的文档,你会发现你可以自己调用它或者改变它的一些参数.

If you look at the doc of the garbage collection, you will see that you can invoke it by yourself or change some of its parameters.

这篇关于是否将 numpy 数组设置为无空闲内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆