gpt4 book ai didi

python - 将文件长时间保留在内存中

转载 作者:行者123 更新时间:2023-12-01 04:23:27 25 4
gpt4 key购买 nike

我正在处理一个相对较大的文件(大约 2GB)。在运行至少 1-2 天的 while 循环中持续需要其内容。

有了足够的 RAM,我在循环之前将整个文件加载到内存中,使用:

f = open(filename)
lines = f.readlines()

while ...
#using different portions of the file (randomly picked)
  • 我想知道如果程序要运行很长时间,这样做是否会遇到内存管理问题。无论需要多久,包含完整内容的文件都会在内存中保持完整吗?如果没有,我还有什么选择?

  • 当然,最初我确实尝试正确执行操作,仅读取循环每次迭代所需的部分,使用 itertools 中的 islice,并使用eek(0) 将迭代器设置回 0 来准备用于循环的后续运行。但由于文件很大,while 循环很长,所以运行速度很慢。

<小时/>

评论后进行更多说明:

当我没有将其加载到内存中时,我基本上在做:

from itertools import islice 
f = open(filename)
while ...:
for line in islice(f, start_line, end_line):
text += line
f.seek(0)

与我将所有内容加载到内存中相比,它真的很慢,如下所示:

lines = f.readlines() 
while...:
for i in range(start_line, end_line): text += lines[i]

最佳答案

您保存在内存中的数据类型是列表,而不是文件对象,因此 Python 将特别小心,当您稍后使用该列表时,不要对其进行垃圾收集。

如果您不按紧密顺序使用它也没关系。 Python 在编译之前会分析代码,他知道你稍后会用到这个列表。

无论如何,如果您在文件对象上使用eek()和tell(),我不明白为什么它会很慢。

除非你的台词像大象一样大。

Seek 将读/写指针移动到您想要的内存块(文件内)。当您随后执行 f.readline() 时,它会直接跳转到那里。

不应该慢。如果你使用它,你将避免其他程序崩溃的可能性,因为 Python 保留了大量内存。

此外,Python 列表并不是完全不确定的。我认为它可以在 32 位 PC 上容纳超过 10**7 个项目。

因此,您有多少行也很重要。

直接从 HD/SSD/Flash 快速随机行读取示例:

from random import randint
from time import sleep

f = open("2GB.file", "rb")
linemap = [] # Keeps the start and end position of each line
for x in f:
linemap.append((f.tell(), len(x)))
# It is slightly faster to have start and length than only start and then f.readline()
# But either way will work OK for you

def getline (index):
line = linemap[index]
f.seek(line[0])
return f.read(line[1])

def getslice (start=0, stop=None):
if stop==None: stop = len(linemap)
howmany = 0
for x in xrange(start, stop): howmany += linemap[x][1]
f.seek(linemap[start][0])
return f.read(howmany).splitlines(1)

while True:
print getline(randint(0, len(linemap)-1))
sleep(2)

当然,速度永远无法与 RAM 的直接访问相媲美。只是要明确一点。但与使用 islice() 的解决方案相比,这快如闪电。虽然您实际上可以使用 islice() 以相同的速度执行相同的操作,但即使这样您也必须进行查找,并且代码会变得有点困惑。

关于python - 将文件长时间保留在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com