示例工程 04-containers-complexity
04-containers-complexity/01-complexity-bench/complexity_bench.py
"""对比 list / set / dict 的成员查找耗时。"""
from __future__ import annotations
import timeit
def build(n: int) -> tuple[list[int], set[int], dict[int, int]]:
"""构造三种容器,元素相同。"""
values = list(range(n))
return values, set(values), {value: value for value in values}
def lookup_ms(n: int, repeat: int = 200) -> dict[str, float]:
"""返回三种容器单次查找的平均耗时(毫秒)。"""
values, value_set, mapping = build(n)
target = n - 1
results: dict[str, float] = {}
for name, statement, local in (
("list", "target in values", {"target": target, "values": values}),
("set", "target in value_set", {"target": target, "value_set": value_set}),
("dict", "target in mapping", {"target": target, "mapping": mapping}),
):
seconds = timeit.timeit(statement, globals=local, number=repeat)
results[name] = seconds / repeat * 1000
return results
def main() -> None:
for name, ms in lookup_ms(10_000).items():
print(f"{name:>5}: {ms * 1000:.2f} µs")
if __name__ == "__main__":
main()