Python deque 滚动窗口计数:明确时间边界,并用 32 项测试验证

10-21 4阅读

“最近五个时间单位内有多少次事件”看起来只要维护一个列表,但真正容易出错的是定义:恰好发生在五个单位之前的事件还算不算?同一时刻发生三次事件应计为一次还是三次?查过较晚时刻以后,还能补录较早事件吗?这篇教程把这些问题写成明确契约,再用 Python 的双端队列 deque 实现一个小型、可测试的事件计数器。

本文只讨论单进程中按非递减时间顺序提交的事件。所有时间均由调用者传入,不读取系统时钟,不访问网络,也不依靠真实等待。它适合学习窗口统计和验证离线事件处理逻辑,不是安全或分布式限流器,也不提供持久化、跨进程一致性或并发事务。

Python deque 滚动窗口计数:明确时间边界,并用 32 项测试验证

配图由图像模型独立生成,是概念示意图,不是实际软件截图。图中右侧窗口外的圆点仅表示待进入的新事件;计数时只统计当前窗口内已经提交的事件。

一、先确定窗口边界与输入契约

令窗口宽度为 width,当前观察时刻为 now,有效区间严格定义为 (now-width, now]。左端不包含,右端包含:width=5、now=10 时,时间戳 5 已经过期,时间戳 6 到 10 仍然有效。我们的时间是离散整数单位,单位可以由业务选择为秒、毫秒或逻辑刻度,但同一个对象内不能混用单位。

width 必须是大于零的内置 int;时间戳必须是大于等于零的内置 int。实现使用 type(value) is int,刻意拒绝 bool、浮点数、字符串以及 int 的子类,不进行隐式取整或转换。这不是唯一可行的接口设计,而是让本文契约足够小且明确。无效输入先抛出异常,不应修改已保存的时间或事件。

append(timestamp) 表示在该时刻新增一次事件,并返回新增后的窗口计数。count(now) 先把观察时间推进到 now,再返回窗口内事件数。两种操作共享同一个非递减时间序列:时间可以相等,不能倒退。尤其要注意,count 不是无副作用的历史查询;即使当前队列为空,count(10) 之后也不能再 append(9)。

同一时间戳代表同一时刻,不代表同一个事件。连续 append(8) 三次就记录三次事件,count(8) 返回 3。这里既不去重,也不附带事件标识;如果业务需要幂等处理,应在另一个明确设计的层面解决,而不是悄悄把相同时间戳合并。

二、为什么用 deque,而不是设置 maxlen

事件按时间排序后,过期事件必然出现在队列左端。新增事件从右端 append,过期事件从左端 popleft;不必在每次查询时扫描所有仍然有效的事件。Python 官方文档说明,deque 两端的追加与弹出操作具有近似 O(1) 的性能,而列表从头部删除会搬移后续元素。参见 Python 3.12 deque 官方文档。

不要用 deque(maxlen=100) 代替“最近五秒”。maxlen 约束的是元素数量,不是时间;同一秒发生一千次事件时,容量为一百的队列会丢掉仍在有效窗口中的事件。本文使用没有固定容量上限的 deque,并且仅按时间条件过期。官方对固定长度队列自动丢弃另一端元素的行为也有说明,这正是这里不能混淆的地方。

三、一份可直接执行的完整文件

把下面全部代码保存为 rolling_window.py,使用 python3.12 rolling_window.py 执行即可。文件包含实现和 32 个 unittest 测试方法,无需安装第三方依赖。本文已在 Python 3.12.14 实际运行通过;后文还会解释固定种子差分测试为什么比只写几个预期值更有帮助。

from collections import deque
import random
import unittest


class RollingEventCounter:
    """Count events in (now - width, now], using nondecreasing calls."""

    def __init__(self, width: int):
        if type(width) is not int:
            raise TypeError('width must be a built-in int, not bool')
        if width <= 0:
            raise ValueError('width must be positive')
        self._width = width
        self._events: deque[int] = deque()
        self._now: int | None = None

    @property
    def width(self) -> int:
        return self._width

    def _advance(self, now: int) -> None:
        if type(now) is not int:
            raise TypeError('timestamp must be a built-in int, not bool')
        if now < 0:
            raise ValueError('timestamp must be nonnegative')
        if self._now is not None and now < self._now:
            raise ValueError('time cannot go backwards')
        cutoff = now - self._width
        while self._events and self._events[0] <= cutoff:
            self._events.popleft()
        self._now = now

    def append(self, timestamp: int) -> int:
        """Advance to timestamp, record one event, return the new count."""
        self._advance(timestamp)
        self._events.append(timestamp)
        return len(self._events)

    def count(self, now: int) -> int:
        """Advance to now and return the count; this is not a pure read."""
        self._advance(now)
        return len(self._events)


class RollingWindowTests(unittest.TestCase):
    def assert_rejected_without_change(self, counter, method, value, error):
        before = (counter._now, tuple(counter._events))
        with self.assertRaises(error):
            getattr(counter, method)(value)
        self.assertEqual(before, (counter._now, tuple(counter._events)))

    def test_empty_at_zero(self):
        self.assertEqual(RollingEventCounter(5).count(0), 0)

    def test_empty_at_large_time(self):
        self.assertEqual(RollingEventCounter(5).count(10**30), 0)

    def test_width_property(self):
        self.assertEqual(RollingEventCounter(7).width, 7)

    def test_width_property_read_only(self):
        c = RollingEventCounter(7)
        with self.assertRaises(AttributeError):
            c.width = 8

    def test_zero_width_rejected(self):
        with self.assertRaises(ValueError):
            RollingEventCounter(0)

    def test_negative_width_rejected(self):
        with self.assertRaises(ValueError):
            RollingEventCounter(-1)

    def test_bool_width_rejected(self):
        for value in (True, False):
            with self.subTest(value=value), self.assertRaises(TypeError):
                RollingEventCounter(value)

    def test_other_width_types_rejected(self):
        for value in (1.0, '1', None, [], {}):
            with self.subTest(value=value), self.assertRaises(TypeError):
                RollingEventCounter(value)

    def test_int_subclass_rejected(self):
        class SpecialInt(int):
            pass
        with self.assertRaises(TypeError):
            RollingEventCounter(SpecialInt(3))
        c = RollingEventCounter(3)
        self.assert_rejected_without_change(c, 'append', SpecialInt(0), TypeError)
        self.assert_rejected_without_change(c, 'count', SpecialInt(0), TypeError)

    def test_append_at_zero(self):
        self.assertEqual(RollingEventCounter(5).append(0), 1)

    def test_same_timestamp_events_are_distinct(self):
        c = RollingEventCounter(5)
        self.assertEqual([c.append(8) for _ in range(3)], [1, 2, 3])
        self.assertEqual(c.count(8), 3)

    def test_right_boundary_included(self):
        c = RollingEventCounter(5)
        c.append(9)
        self.assertEqual(c.count(9), 1)

    def test_left_boundary_excluded(self):
        c = RollingEventCounter(5)
        c.append(9)
        self.assertEqual(c.count(14), 0)

    def test_just_before_expiration(self):
        c = RollingEventCounter(5)
        c.append(9)
        self.assertEqual(c.count(13), 1)

    def test_partial_expiration(self):
        c = RollingEventCounter(5)
        for t in (3, 4, 5, 8):
            c.append(t)
        self.assertEqual(c.count(9), 2)
        self.assertEqual(list(c._events), [5, 8])

    def test_all_same_timestamp_expire(self):
        c = RollingEventCounter(5)
        for _ in range(4):
            c.append(9)
        self.assertEqual(c.count(14), 0)

    def test_append_expires_old_events_first(self):
        c = RollingEventCounter(5)
        c.append(2)
        c.append(3)
        self.assertEqual(c.append(7), 2)
        self.assertEqual(list(c._events), [3, 7])

    def test_width_one(self):
        c = RollingEventCounter(1)
        self.assertEqual(c.append(0), 1)
        self.assertEqual(c.append(0), 2)
        self.assertEqual(c.append(1), 1)
        self.assertEqual(c.count(2), 0)

    def test_repeated_query_same_time(self):
        c = RollingEventCounter(5)
        c.append(2)
        self.assertEqual([c.count(4) for _ in range(3)], [1, 1, 1])

    def test_query_then_append_same_time(self):
        c = RollingEventCounter(5)
        self.assertEqual(c.count(10), 0)
        self.assertEqual(c.append(10), 1)
        self.assertEqual(c.count(10), 1)

    def test_append_backwards_rejected(self):
        c = RollingEventCounter(5)
        c.append(10)
        self.assert_rejected_without_change(c, 'append', 9, ValueError)

    def test_query_backwards_rejected(self):
        c = RollingEventCounter(5)
        c.append(10)
        self.assert_rejected_without_change(c, 'count', 9, ValueError)

    def test_query_advances_empty_clock(self):
        c = RollingEventCounter(5)
        c.count(10)
        self.assert_rejected_without_change(c, 'append', 9, ValueError)
        self.assert_rejected_without_change(c, 'count', 9, ValueError)

    def test_query_prevents_late_append(self):
        c = RollingEventCounter(10)
        c.append(1)
        c.count(5)
        self.assert_rejected_without_change(c, 'append', 4, ValueError)
        self.assertEqual(c.append(5), 2)

    def test_negative_timestamps_rejected(self):
        for method in ('append', 'count'):
            c = RollingEventCounter(5)
            self.assert_rejected_without_change(c, method, -1, ValueError)

    def test_bool_timestamps_rejected(self):
        for method in ('append', 'count'):
            for value in (True, False):
                c = RollingEventCounter(5)
                self.assert_rejected_without_change(c, method, value, TypeError)

    def test_other_timestamp_types_rejected(self):
        c = RollingEventCounter(5)
        c.append(3)
        for method in ('append', 'count'):
            for value in (3.0, '3', None, [], {}):
                with self.subTest(method=method, value=value):
                    self.assert_rejected_without_change(c, method, value, TypeError)

    def test_large_time_jump(self):
        c = RollingEventCounter(5)
        c.append(0)
        self.assertEqual(c.count(10**30), 0)
        self.assertEqual(c.append(10**30), 1)

    def test_large_width(self):
        c = RollingEventCounter(10**30)
        c.append(0)
        self.assertEqual(c.count(10**30 - 1), 1)
        self.assertEqual(c.count(10**30), 0)

    def test_independent_instances(self):
        a = RollingEventCounter(5)
        b = RollingEventCounter(5)
        a.append(10)
        self.assertEqual(b.append(0), 1)
        self.assertEqual(a.count(10), 1)

    def test_no_fixed_capacity_silent_loss(self):
        c = RollingEventCounter(5)
        for _ in range(2000):
            c.append(7)
        self.assertIsNone(c._events.maxlen)
        self.assertEqual(c.count(7), 2000)
        self.assertEqual(c.count(12), 0)

    def test_seeded_list_reference(self):
        # The reference keeps full history, not an expiring deque.
        for seed in range(40):
            rng = random.Random(seed)
            width = rng.choice((1, 2, 5, 17, 100))
            c = RollingEventCounter(width)
            history = []
            now = 0
            for step in range(500):
                now += rng.choice((0, 0, 1, 2, width, width + 1))
                if rng.random() < 0.65:
                    history.append(now)
                    actual = c.append(now)
                else:
                    actual = c.count(now)
                expected = [t for t in history if now - width < t <= now]
                with self.subTest(seed=seed, step=step):
                    self.assertEqual(actual, len(expected))
                    self.assertEqual(list(c._events), expected)
                    self.assertEqual(c._now, now)
            self.assertEqual(c.count(now + width), 0)


if __name__ == '__main__':
    unittest.main(verbosity=2)

四、过期循环的正确性来自三个不变量

每次成功调用结束后,队列中的时间戳保持非递减;所有保留时间戳都满足 now-width < t <= now;队列中每个元素恰好对应一次已提交且尚未过期的事件。第一次调用也适用,只是初始观察时刻为 None,允许直接从任意非负时刻开始。

推进时先验证时间,再计算 cutoff=now-width。由于左端点不属于窗口,删除条件必须是 t <= cutoff,而不是 t < cutoff。最左端已经有效时,后面的时间戳只会更大,所以循环可以立即停止。append 在清理结束后加入当前时间戳;宽度严格为正,因此新事件必然属于右闭窗口。

验证发生在清理之前还有一个价值:提交错误参数或倒退时间不会先删数据再报错。测试不仅检查异常类型,也比较调用前后的观察时刻与队列快照。这里检查的是参数校验失败后的状态保持,不承诺内存耗尽等运行环境故障下具有事务回滚能力。

五、用完整历史列表建立独立参照

边界测试覆盖空窗口、零时刻、同刻重复事件、左端恰好过期、右端保留、批量过期、宽度为一、巨大时间跳跃,以及查询推进后拒绝迟到事件。最后一个测试再使用 40 个固定随机种子,每个执行 500 步,共比较 20,000 次操作。

参照模型故意不使用相同的“左端弹出”算法。它保留已追加事件的完整历史,每一步用列表筛选 now-width < t <= now,独立算出应保留的事件和数量。测试同时比较返回值、实际保留序列和观察时刻;随机步长包含零、窗口宽度以及超过窗口宽度的跳跃,因而覆盖同刻操作和大面积过期。固定种子让失败能够复现,但通过这些测试并不意味着穷尽了所有输入或证明了生产环境安全性。

本次执行结果为 Ran 32 tests,结尾为 OK。发布前又从文章 HTML 中提取并解码代码,与原始文件逐字节比较,然后使用 Python 3.12.14 再次执行通过。这样能区分“本地源文件正确”和“读者复制到的代码正确”,避免空格、比较符号或引号在排版时被损坏。

六、性能、内存与适用边界

一次调用如果过期了 k 个事件,实际需要做 k 次删除,因此单次最坏时间是 O(k),不能声称每次调用都严格 O(1)。从一段成功操作序列看,每次事件只追加一次、最多删除一次;忽略大整数运算的位数成本,把时间戳操作视为常数成本时,N 次追加和 Q 次查询的累计工作量为 O(N+Q),摊还到每次调用是 O(1)。

空间复杂度是 O(M),M 是最近一次调用后仍被保留的事件数,绝不是固定 O(1)。单位时间内事件越密集,内存越多;若不停地追加同一个时间戳,窗口也不会自然过期。没有后续 append 或 count 调用时,这个纯对象不会在后台自动清理,现实时间流逝并不改变其状态。Python 任意精度整数的位数也会影响单个时间戳的存储成本。

官方文档提及 deque 的单次两端追加与弹出操作支持线程安全,不等于本类由“校验、清理、更新时间、追加”组成的整套操作是线程安全的。本例没有锁,不能直接作为多线程共享计数器。它也不接收乱序事件,不支持回看过去的窗口,不自动纠正墙上时钟回拨。若业务要处理迟到数据、重启恢复、多机器协同或请求准入决策,需要先补齐各自的语义和一致性设计,而不是把这个教学计数器直接改名为限流系统。

参考资料

来源核对日期:2026 年 10 月 21 日(北京时间)。实现、接口约束与测试为本文原创示例;文档用于核实标准库行为,不作为性能实测或生产安全保证。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。