我可以在Python中提高有限长度双端队列(循环缓冲区)中随机访问的速度吗?

时间:2011-06-21 15:34:14

标签: python data-structures

我正在编写一个Python中的小型日志抓取程序,该程序处理滚动日志文件并将偏移量存储在文件中以用于感兴趣的行。

我的原始解决方案在大文件上运行得相当快,但我没有清除存储的方法,这意味着如果程序继续运行,内存使用量会稳定增加,直到程序消耗掉所有内存可用。我的解决方案是使用collections.deque并设置maxlen,以便列表作为循环缓冲区运行,丢弃最旧的日志,因为有更多的日志。

虽然这解决了内存问题,但我遇到了通过索引从双端队列调用项目时的重大性能损失。例如,此代码运行速度比旧的等效代码慢得多,其中self.loglines不是deque。有没有办法提高它的速度,或者做一个循环缓冲区,其中随机访问是一个恒定时间操作(而不是,我假设,O(n))?

    def get_logline(self, lineno):
            """Gets the logline at the given line number.

            Arguments:
            lineno - The index of the logline to retrieve

            Returns: A string containing the logline at the given line number
            """

            start = self.loglines[lineno].start
            end = self.loglines[lineno+1].start
            size = end - start
            if self._logfile.closed:
                    self._logfile = open(self.logpath, "r")
            self._logfile.seek(start)
            logline = self._logfile.read(size)
            return logline

1 个答案:

答案 0 :(得分:2)

与所有双链表一样,collections.deque中的随机访问是O(n)。考虑使用有界列表列表,以便即使有数十万个条目,也可以及时清除旧条目(del outer[0])。