文件在关闭后保留在内存中



我想在Kaggle上使用Jupyter Notebook循环处理许多mp3文件。但是,将 mp3 文件作为二进制文件读取似乎确实会将文件保留在内存中,即使在函数返回并且文件正确关闭之后也是如此。这会导致内存使用量随着处理的每个文件而增长。问题似乎出在read()功能上,因为pass不会导致任何内存使用量增长。

在循环浏览 mp3 文件时,内存使用量增长等于正在处理的文件的大小,这暗示文件保留在内存中。

如何在函数返回后读取文件而不将其保留在内存中?

def read_mp3_as_bin(fname):
with open(fname, "rb") as f:
data = f.read() # when using 'pass' memory usage doesn't grow
print(f.closed)
return
for fname in file_names: # file_names are 25K paths to the mp3 files
read_mp3_as_bin(fname)

"解决方案">

我确实在本地运行了此代码,并且根本没有内存使用量增长。因此,看起来 Kaggle 确实以不同的方式处理文件,因为这是此测试中唯一的变量。我将尝试找出为什么这段代码在 Kaggle 上的行为不同,当我了解更多时会通知您。

我很确定你测量的内存使用错误。

我创建了 3 个虚拟文件,每个文件有 50MB,并在它们上运行你的代码,输出每次循环迭代的函数内部和外部的内存使用情况,结果与文件关闭后释放的内存一致。

为了测量内存使用情况,我使用了此处建议的解决方案,并且要创建虚拟文件,我只是按照这篇博文的建议运行truncate -s 50M test_1.txt

看一看:

import os
import psutil

def read_mp3_as_bin(fname):
with open(fname, "rb") as f:
data = f.read()  # when using 'pass' memory usage doesn't grow
if data:
print("read data")
process = psutil.Process(os.getpid())
print(f"inside the function, it is using {process.memory_info().rss / 1024 / 1024} MB")  # in Megabytes
return

file_names = ['test_1.txt', 'test_2.txt', 'test_3.txt']
for fname in file_names:  # file_names are 25K paths to the mp3 files
read_mp3_as_bin(fname)
process = psutil.Process(os.getpid())
print(f"outside the function, it is using {process.memory_info().rss / 1024 / 1024} MB")  # in Megabytes

输出:

read data
inside the function, it is using 61.77734375 MB
outside the function, it is using 11.91015625 MB
read data
inside the function, it is using 61.6640625 MB
outside the function, it is using 11.9140625 MB
read data
inside the function, it is using 61.66796875 MB
outside the function, it is using 11.91796875 MB

最新更新