Python:islice 的性能问题

标签 python performance csv python-itertools

使用以下代码,当我增加 islice 中的起始行时,我发现执行时间越来越长。例如,start_row 为 4 将在 1 秒内执行,但 start_row 为 500004 将花费 11 秒。为什么会发生这种情况?有没有更快的方法来做到这一点?我希望能够迭代大型 CSV 文件(几 GB)中的多个行范围并进行一些计算。

import csv
import itertools
from collections import deque
import time

my_queue = deque()

start_row = 500004
stop_row = start_row + 50000

with open('test.csv', 'rb') as fin:
    #load into csv's reader
    csv_f = csv.reader(fin)

    #start logging time for performance
    start = time.time()

    for row in itertools.islice(csv_f, start_row, stop_row):
        my_queue.append(float(row[4])*float(row[10]))

    #stop logging time
    end = time.time()
    #display performance
    print "Initial queue populating time: %.2f" % (end-start)

最佳答案

For example, a start_row of 4 will execute in 1s but a start_row of 500004 will take 11s

这就是 islice 的智能。或者懒惰,取决于您喜欢哪个术语。

事实是,文件“只是”硬盘驱动器上的字节字符串。他们没有任何内部组织。 \n 只是那个很长很长的字符串中的另一组字节。 如果不查看任何特定行之前的所有信息,就无法访​​问该行(除非您的行的长度完全相同,在这种情况下您可以使用 file.seek)。

4号线?查找第 4 行很快,您的计算机只需要查找 3 \n。 50004 号线?您的计算机必须通读该文件,直到找到 500003 \n。没有办法解决这个问题,如果有人告诉你相反的情况,他们要么拥有某种其他类型的量子计算机,要么他们的计算机正在像世界上所有其他计算机一样在背后读取文件。

至于你能做些什么:在尝试捕获行进行迭代时尽量保持聪明。聪明,又懒。安排您的请求,以便您只需遍历文件一次,并在提取所需数据后立即关闭文件。 (顺便说一下,islice 完成了所有这些工作。)

在Python中

lines_I_want = [(start1, stop1), (start2, stop2),...]
with f as open(filename):
     for i,j in enumerate(f):
          if i >= lines_I_want[0][0]:
              if i >= lines_I_want[0][1]:
                   lines_I_want.pop(0)
                   if not lines_I_want: #list is empty
                         break
              else:
                   #j is a line I want. Do something

如果您可以控制创建该文件,请将每一行设置为相同的长度,以便您可以查找。或者使用数据库。

关于Python:islice 的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225782/

相关文章:

python - 通过pycomm读取标签时超时

python - 在 Python 中从 Url 获取图像尺寸

c# - C# 中的 Monitor.Pulse 似乎不理想 : must be in lock scope

android - 电晕表现?

c++ - 使用 C++ 将 .csv 中的数据读入可用格式

python - Opencv python 不正确的 block 大小

python tkinter 从命令中使用的函数返回值

windows - 用于建立连接的端口数的性能计数器

c# - 替换逗号分隔文件中的特定逗号

Python Datacompy 库 : how to save report string into a csv file?