python - 内存泄漏(?)Python 3.2

标签 python memory

您好,我是 python 的新手,我已经阅读了足够多的关于特定主题的帖子,但没有一个有具体的答案。 (使用py 64位3.2版)

我有一个很大的输入,我在循环中读取它,当我读取文件时,我创建了组,我将其附加到 List 。我处理列表,然后将其存储在一个文件中。我取消引用列表 (List = None) 并将其删除。我什至手动调用 gc 收集器。问题是内存仍在使用。交换空间,Ram 变得疯狂。

for line in file: # read line by line
        temp_buffer = line.split() # split elements
        for word in temp_buffer: #enumerate (?)
             if not l1: # list is empty
                 l1.append(str(word)) #store '-' to list 
             else:      # list is not empty
                 tempp = l1.pop(0)
                 l1.insert(0,"-0")
                 l1.sort(key=int)
                 l2 = term_compress(l1)

                 l1 = None # delete referrences
                 del l1    # delete struct

                 print(" ".join(str(i) for i in l2) , file=testfile) # print for every term in file
                 l2 = None # delete referrences
                 del l2    # delete struct

                 gc.collect() # run garbagge collector (free RAM)
                 l1 = [] 
                 l2 = []
                 l1.append(str(word))

我做错了什么?

编辑

示例输入:

-a 1 2 3 4 5 6 7 8 9 10

-n 7 8 9 10 11 12 13 14 15 ...

输出

-a 1# 10#

-n 7# 15#

最佳答案

这很可能不是传统意义上的编程错误中的内存/引用泄漏。您可能看到的是底层 C 运行时积极保留 Python 在循环期间代表您分配的堆内存。预计您可能需要再次使用该内存。持有它比将它还给操作系统内核只是一次又一次地请求它要便宜。

因此,简而言之,即使您的对象已在 Python runtime 中被垃圾回收, underlying C runtime卡在堆内存上,以防您的程序再次需要它。

来自 glibc 文档:

Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc.

从这个意义上说,循环后操作系统报告的内存利用率基本上就是您的“内存利用率峰值”。如果您认为它太高,那么您必须考虑重新设计您的程序以限制其峰值内存使用量。这通常是使用某种流式传输或缓冲设计来实现的,您可以一次对较小的数据 block 进行操作。

免责声明,以上是外行版本,显然是针对各种 Python、C 和操作系统的具体实现。

关于python - 内存泄漏(?)Python 3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310146/

相关文章:

Javascript:将类/对象引用设置为 NULL,内存中的子对象/类会发生什么?

python - Dropbox API 上的 401 未经授权

python - PyTorch 和 Numpy 中的张量输入选择逻辑分歧

python - 枕头滴灌领域用python3.2 django1.8

c# - XElement.ToString() 导致 System.OutOfMemoryException

c++ - 全局范围内的对象在程序退出时导致崩溃

python - matplotlib 的 rcParams 中的 "rc"代表什么?

python - 为什么这个数组的值在作为参数传递给函数时会发生变化?

windows - Realloc() 在 Windows 中没有正确释放内存

iphone - 这就是 Objective-C 中垃圾收集的全部内容吗?