是否将numpy数组设置为“无可用内存"? [英] Does setting numpy arrays to None free memory?

查看:109
本文介绍了是否将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)

另外:有时我会切分矩阵,计算出一些东西,然后将值放入缓冲区(一个列表,因为它一直被附加).因此,将列表设置为无"肯定会释放内存,对吗?

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"?

推荐答案

您肯定想看看

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

实际情况是,与分配None或使用del无关,通过1减少了对内存空间引用的计数器.当此计数器达到0时,垃圾回收器将在将来free内存空间.唯一的区别是,使用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天全站免登陆