gpt4 book ai didi

python 3.7 : Performance tuning on huge data files comparison

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:42 25 4
gpt4 key购买 nike

我有两个大小为 3 GB 的 csv 文件来比较和存储第三个中的差异文件。

Python 代码:

with open('JUN-01.csv', 'r') as f1:
file1 = f1.readlines()

with open('JUN-02.csv', 'r') as f2:
file2 = f2.readlines()

with open('JUN_Updates.csv', 'w') as outFile:
outFile.write(file1[0])
for line in file2:
if line not in file1:
outFile.write(line)

执行时间:45 分钟 仍在运行...

最佳答案

不确定是否为时已晚,但它来了。

我看到您正在内存中加载 2 个数组,以及您的完整文件。如果你说它们每个大约 3 GB,那就是试图在 RAM 中填充 6 GB 并且可能进入交换空间。

此外,即使您成功加载了文件,您也在尝试进行 ~ L1xL2 字符串比较(L1 和 L2 是行数)。

我在 1.2 GB(330 万行)中运行了以下代码并在几秒钟内完成。它使用字符串哈希,并且只在 RAM 中加载一组 L1 整数 32。

技巧在这里完成,在将 hashstring 函数应用于文件中的每一行之后创建一个 set()(标题除外,您似乎将其添加到输出中)。

file1 = set(map(hashstring, f1))

请注意,我正在将文件与自身进行比较(f2 加载与 f1 相同的文件)。让我知道是否有帮助。

from zlib import adler32

def hashstring(s):
return adler32(s.encode('utf-8'))

with open('haproxy.log.1', 'r') as f1:
heading = f1.readline()
print(f'Heading: {heading}')
print('Hashing')
file1 = set(map(hashstring, f1))
print(f'Hashed: {len(file1)}')

with open('updates.log', 'w') as outFile:
count = 0
outFile.write(heading)
with open ('haproxy.log.1', 'r') as f2:
for line in f2:
if hashstring(line) not in file1:
outFile.write(line)
count += 1
if 0 == count % 10000:
print(f'Checked: {count}')

关于 python 3.7 : Performance tuning on huge data files comparison,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50678710/

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