简体   繁体   English

如何删除python函数中的对象?

[英]How to delete an object in python function?

I am working with very large numpy/scipy arrays that take up a huge junk of memory. 我正在使用非常大的numpy / scipy数组,占用大量的内存。 Suppose my code looks something like the following: 假设我的代码如下所示:

def do_something(a):
  a = a / a.sum() #new memory is allocated
  #I don't need the original a now anylonger, how to delete it?
  #do a lot more stuff

#a = super large numpy array
do_something(a)
print a #still the same as originally (as passed by value)

So I am calling a function with a huge numpy array. 所以我用一个巨大的numpy数组调用一个函数。 The function then processes the array in some way or the other, but the original object is still kept in memory. 然后该函数以某种方式处理数组,但原始对象仍保留在内存中。 Is there any way to free the memory inside the function; 有没有办法释放函数内部的内存; deleting the reference does not work. 删除引用不起作用。

What you want cannot be done; 你想要什么不能做; Python will only free the memory when all references to the array object are gone, and you cannot delete the a reference in the calling namespace from the function. Python只会在对数组对象的所有引用都消失后释放内存,并且不能从函数中删除调用命名空间中a引用。

Instead, break up your problem into smaller steps. 相反,将您的问题分解为更小的步骤。 Do your calculations on a with one function, delete a then, then call another function to do the rest of the work. 请您在计算a有一个功能,可以删除a则,然后调用另一个函数做的工作的其余部分。

Python works with a simple GC algorithm, basically it has a reference counting (it has a generational GC too, but that's not the case), that means that every reference to the object increment a counter, and every object out of scope decrement the scope. Python使用一个简单的GC算法,基本上它有一个引用计数(它也有一个世代GC,但事实并非如此),这意味着每个对象的引用都会增加一个计数器,并且每个对象超出范围会减少范围。 The memory is deallocated only after the counter reach 0. 仅在计数器达到0后才释放存储器。

so while you've a reference to that object, it'll keep on memory. 所以当你对这个对象的引用时,它会保留在内存中。

In your case the caller of do_something still have a reference to the object, if you want that this variable gone you can reduce the scope of that variable. 在你的情况下,do_something的调用者仍然有对象的引用,如果你想要这个变量消失,你可以减少该变量的范围。

If you suspect of memory leaks you can set the DEBUG_LEAK flag and inspect the output, more info here: https://docs.python.org/2/library/gc.html 如果您怀疑内存泄漏,可以设置DEBUG_LEAK标志并检查输出,更多信息请访问: https ://docs.python.org/2/library/gc.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM