我可以提高Python中boundedlength deque(循环缓冲区)中随机访问的速度吗?

2024-09-25 16:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我最初的解决方案是在大文件上运行得相当快,但我没有清除存储的方法,这意味着如果程序继续运行,内存使用量将稳步增加,直到程序耗尽所有可用内存。我的解决方案是将collections.dequemaxlen一起使用,这样列表将作为一个循环缓冲区来操作,当更多日志行出现时,丢弃最旧的日志行。在

虽然这修复了内存问题,但在调用deque by index中的项时,我面临着一个严重的性能损失。例如,此代码比旧的等效代码运行速度慢得多,其中self.loglines公司不是德克。有没有办法提高它的速度,或者制作一个循环缓冲区,其中随机存取是一个固定的时间操作(而不是,我假设是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

Tags: 文件the内存self程序index解决方案start