简体   繁体   English

删除变量不会从 RAM 内存中擦除其内存

[英]Deleting variable does not erase its memory from RAM memory

I am using Python (Canopy) extensively for Earth science application.我在地球科学应用中广泛使用 Python(Canopy)。 Because my application is memory consuming, I am trying find way to erase variable that I don't need any more in my programs, I tried to use del command to erase the variable memory, but I found that space used by Canopy is still the same.因为我的应用程序是内存消耗,我想办法擦除我的程序中不再需要的变量,我尝试使用 del 命令擦除变量内存,但我发现 Canopy 使用的空间仍然是相同的。 Any ideas about how to erase variable completely from the memory.关于如何从内存中完全擦除变量的任何想法。 thanks谢谢

You can't manually nuke an object from your memory in Python! 你无法在Python中手动修改内存中的对象!

The Python Garbage Collector (GC) will automatically free up memory of objects that have no existing references any more (implementation details differ per interpreter). Python垃圾收集器(GC)将自动释放没有现有引用的对象的内存(每个解释器的实现细节不同)。 It's periodically checking for abandoned objects in background without your interaction. 它会在没有您交互的情况下定期检查背景中被遗弃的对象。

So to get an object recycled, you have to eliminate all references to it by assigning a different value (eg None) to all variables that pointed to the object. 因此,要使对象回收,必须通过为指向对象的所有变量分配不同的值(例如None)来消除对它的所有引用。 You can also delete a variable name using the del statement, but as you already noticed, this only deletes the name with the reference, but not the object and its data itself. 您也可以使用del语句删除变量名,但正如您已经注意到的,这只会删除带引号的名称,而不会删除对象及其数据本身。 Only the GC can do that. 只有GC可以做到这一点。

Now, it is possible to do it manually .现在,可以手动进行 To do that, you need to do it in two steps:为此,您需要分两步完成:

  1. use the command del to remove the variable from the workspace使用命令del从工作区中删除变量
  2. use the comand gc.collect to run the garbage collector and clear the ram memory使用命令gc.collect运行垃圾收集器并清除 ram 内存

A code example:一个代码示例:

import numpy as np
import gc

a = np.array([1,2,3])
del a
gc.collect()

More info: link更多信息:链接

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

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