基于Python有序字典的RPC请求超时检测算法时间复杂度分析
RPC请求超时检测算法的时间复杂度疑问
有一串RPC请求流被记录,每条日志条目格式为
{rpc_id, timestamp, type (start or end)}。给定超时值T,需要尽可能早地判断是否有请求超时。
示例:
id - time - type 0 - 0 - Start 1 - 1 - Start 0 - 2 - End 2 - 6 - Start 1 - 7 - End Timeout = 3 答案: {1, 6}(确定id为1的请求在时间6时超时)
原讨论中有使用双向链表+哈希表实现的O(n)复杂度方案,我利用Python字典(dict)保留插入顺序的特性,只用字典作为唯一数据结构实现了如下代码:
from dataclasses import dataclass @dataclass(frozen=True, slots=True) class LogEntry: rpc_id: int timestamp: int action: str class LogProcessor: def __init__(self, timeout: int): self.entries = {} self.timeout = timeout def process_log_entry(self, entry: LogEntry) -> list[LogEntry]: if entry.action == 'Start': self.entries[entry.rpc_id] = entry elif entry.rpc_id in self.entries and entry.timestamp - self.entries[entry.rpc_id].timestamp <= self.timeout: del self.entries[entry.rpc_id] timed_out = [] for k, v in self.entries.items(): if entry.timestamp - v.timestamp <= self.timeout: break timed_out.append(v) for e in timed_out: del self.entries[e.rpc_id] return timed_out log_processor = LogProcessor(timeout=3) assert log_processor.process_log_entry(LogEntry(1, 0, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(2, 1, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(1, 2, 'End')) == [] assert log_processor.process_log_entry(LogEntry(3, 6, 'Start')) == [LogEntry(2, 1, 'Start')]
请问该算法的时间复杂度是否仍为O(n)?
内容的提问来源于stack exchange,提问作者Eugene Yarmash
相关产品推荐
相关产品推荐

