lru_cache_benchmark.py ダウンロード/コピー

lru_cache_benchmark.py をダウンロード

lru_cache_benchmark.py
lru_cache_benchmark.py
  1#!/usr/bin/env python3
  2"""lru_cache のヒット数・実計算回数・実行時間を比較するベンチマーク。"""
  3
  4from __future__ import annotations
  5
  6import argparse
  7from functools import lru_cache
  8import math
  9import random
 10import statistics
 11import time
 12
 13
 14# 実際に重い関数本体が呼ばれた回数を数える。
 15plain_evaluations = 0
 16cached_evaluations = 0
 17
 18
 19def costly_exp_plain(x: float, n_exp: int) -> float:
 20    """キャッシュなし版。math.exp(x) を n_exp 回呼び出す。"""
 21    global plain_evaluations
 22    plain_evaluations += 1
 23    y = 0.0
 24    for _ in range(n_exp):
 25        y = math.exp(x)
 26    return y
 27
 28
 29@lru_cache(maxsize=None)
 30def costly_exp_cached(x_rounded: float, n_exp: int) -> float:
 31    """丸め済み引数をキーにするキャッシュ版の重い本体。"""
 32    global cached_evaluations
 33    cached_evaluations += 1
 34    y = 0.0
 35    for _ in range(n_exp):
 36        y = math.exp(x_rounded)
 37    return y
 38
 39
 40def f_with_cache(x: float, decimals: int, n_exp: int) -> float:
 41    """入力を小数第 decimals 位へ丸めてからキャッシュを参照する。"""
 42    return costly_exp_cached(round(x, decimals), n_exp)
 43
 44
 45def median_time(func, xs: list[float], repeat: int) -> tuple[float, float]:
 46    """func を各 x に適用した時間の median と、結果確認用の和を返す。"""
 47    elapsed = []
 48    checksum = 0.0
 49    for _ in range(repeat):
 50        total = 0.0
 51        t0 = time.perf_counter()
 52        for x in xs:
 53            total += func(x)
 54        elapsed.append(time.perf_counter() - t0)
 55        checksum = total
 56    return statistics.median(elapsed), checksum
 57
 58
 59def main() -> None:
 60    parser = argparse.ArgumentParser(
 61        description="丸めた引数に lru_cache を使う効果を測定します。"
 62    )
 63    parser.add_argument("-n", "--n", type=int, default=100_000,
 64                        help="[0, 1] 一様乱数の個数 (default: 100000)")
 65    parser.add_argument("--decimals", type=int, default=3,
 66                        help="キャッシュキーへ使う小数点以下桁数 (default: 3)")
 67    parser.add_argument("--n-exp", type=int, default=100,
 68                        help="1回の本体計算で呼ぶ exp(x) の回数 (default: 100)")
 69    parser.add_argument("-r", "--repeat", type=int, default=3,
 70                        help="時間測定の繰り返し回数 (default: 3)")
 71    parser.add_argument("--seed", type=int, default=12345,
 72                        help="乱数シード (default: 12345)")
 73    args = parser.parse_args()
 74
 75    if args.n <= 0 or args.repeat <= 0 or args.n_exp <= 0 or args.decimals < 0:
 76        parser.error("n, repeat, n-exp は正、decimals は 0 以上にしてください。")
 77
 78    rng = random.Random(args.seed)
 79    xs = [rng.random() for _ in range(args.n)]
 80
 81    global plain_evaluations, cached_evaluations
 82    plain_evaluations = 0
 83    t_plain, sum_plain = median_time(
 84        lambda x: costly_exp_plain(x, args.n_exp), xs, args.repeat
 85    )
 86
 87    # 各測定を「空のキャッシュ」から始める。こうすると、繰り返し測定でも
 88    # キャッシュ構築を含む公平な時間比較になる。
 89    cached_evaluations = 0
 90    cached_elapsed = []
 91    sum_cached = 0.0
 92    info = None
 93    for _ in range(args.repeat):
 94        costly_exp_cached.cache_clear()
 95        total = 0.0
 96        t0 = time.perf_counter()
 97        for x in xs:
 98            total += f_with_cache(x, args.decimals, args.n_exp)
 99        cached_elapsed.append(time.perf_counter() - t0)
100        sum_cached = total
101        info = costly_exp_cached.cache_info()
102    t_cached = statistics.median(cached_elapsed)
103
104    print(f"N={args.n:,}, repeat={args.repeat}, exp calls per evaluation={args.n_exp}")
105    print(f"cache key: round(x, {args.decimals})")
106    print()
107    print("case                         requests  actual evaluations   median time")
108    print("-" * 72)
109    print(f"no cache                   {args.n * args.repeat:10,}  {plain_evaluations:17,}  {t_plain:11.6f} s")
110    print(f"lru_cache + rounded key    {args.n * args.repeat:10,}  {cached_evaluations:17,}  {t_cached:11.6f} s")
111    print()
112    print(f"lru_cache info (one run): hits={info.hits:,}, misses={info.misses:,}, currsize={info.currsize:,}")
113    print(f"speedup (median): {t_plain / t_cached:.2f} x")
114    print(f"checksums (not physically meaningful): {sum_plain:.6g}, {sum_cached:.6g}")
115
116
117if __name__ == "__main__":
118    main()