【问题标题】:python file operation slowing down on massive text filespython文件操作在大量文本文件上减慢
【发布时间】:2020-11-03 17:25:33
【问题描述】:

这段 Python 代码运行的时间越长,速度就越慢。

谁能告诉我为什么?

我希望它不会为我查询的每一行重新索引并从头开始计数,我认为这将是某种文件流?!

从 10k 到 20k 需要 2 秒。从 300k 到 310k 大约需要 5 分钟。并且变得更糟。 代码仅在 ELSE 部分中运行到该点,并且“listoflines”在该点是恒定的(列表中的 850000 行)并且类型为“list []”以及“偏移”只是一个恒定的“int”那一点。

源文件有数百万行,最多超过 2000 万行。

'dummyline not in listoflines' 每次都应该花费相同的时间。

with open(filename, "rt") as source:
    for dummyline in source:
        if (len(dummyline) > 1) and (dummyline not in listoflines):
            # RUN compute
            # this part is not reached where I have the problem
        else:
            if dummyalreadycheckedcounter % 10000 == 0:
            print ("%d/%d: %s already checked or not valid " % (dummyalreadycheckedcounter, offset, dummyline) )
            dummyalreadycheckedcounter = dummyalreadycheckedcounter +1

【问题讨论】:

  • 我猜测记忆中的某些东西可能正在增长,并且细节隐藏在您编辑掉的位中。即使您显示的内容也没有正确缩进,这表明您也已经编辑了“else”块内的行。
  • thx,虽然我看不出上面的缩进有什么问题,但它仍然只是工作代码的复制粘贴..它确实在做它应该做的事情,没有别的..

标签: python list python-textprocessing


【解决方案1】:

实际上 in 对 list 的操作每次都不一样,实际上它是 O(n) 所以随着你添加它会变得越来越慢

你想使用 set 看这里https://wiki.python.org/moin/TimeComplexity

你没有要求这个,但我建议把它变成一个处理管道,这样你的计算部分就不会与去重逻辑混合

def dedupped_stream(filename):
    seen = set()
    with open(filename, "rt") as source:
        for each_line in source:
            if len(line)>1 and each_line not in seen:
                seen.add(each_line)
                yield each_line

那么你就可以了

for line in dedupped_stream(...):
    ...

您根本不必担心这里的重复数据删除

【讨论】:

    【解决方案2】:

    与@Sedy Vlk 意见相同。 改用哈希(即python中的字典)。

    clines_count = {l: 0 for l in clines}
    for line in nlines:
        if len(line) > 1 and line in clines_count:
            pass
        else:
            if counter % 10000 == 0:
                print ("%d: %s already checked or not valid " % (counter, line) )
            counter += 1
    

    【讨论】:

    • 这里根本不需要字典,只需要一套和.add(line_you_saw)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多