You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:24