我正在用Python编写一个小的日志抓取程序,它处理一个滚动日志文件,并在文件中存储感兴趣行的偏移量。在
我最初的解决方案是在大文件上运行得相当快,但我没有清除存储的方法,这意味着如果程序继续运行,内存使用量将稳步增加,直到程序耗尽所有可用内存。我的解决方案是将collections.deque
与maxlen
一起使用,这样列表将作为一个循环缓冲区来操作,当更多日志行出现时,丢弃最旧的日志行。在
虽然这修复了内存问题,但在调用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
与所有的双链表一样,
collections.deque
中的随机访问是O(n)。考虑使用一个有界列表的列表,这样即使有数十万个条目,旧条目(del outer[0]
)的清除仍然可以及时进行。在相关问题 更多 >
编程相关推荐