python 3.7 : Performance tuning on huge data files comparison

标签 python python-3.x

我有两个大小为 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/

相关文章:

python - @ 运算符与 ndarray 或矩阵操作数出现新的意外操作数错误

python - 如何确保用户输入了数字?

python - 在 Python 中使用 BS4 解析 HTML

python - SciPy curve_fit 运行时错误,停止迭代

python - 将 "Ctrl-A"放入 Python shell 脚本中

python-3.x - 比较包含字符串的数据帧行

Python:导入包含包的实际模块对象,而不命名它

python - 我可以在打印语句中包含一个 for 循环吗?

python - 为什么在 PIL(low) 中读取图像会破坏 Flask 图像终点?

python - 用PIL制作缩略图,增强方式