lru_cache_benchmark.py ダウンロード/コピー
lru_cache_benchmark.py をダウンロード
lru_cache_benchmark.py
lru_cache_benchmark.py
1#!/usr/bin/env python3
2"""
3概要:
4 lru_cache のヒット数、実計算回数、実行時間を比較するベンチマークスクリプトです。
5詳細説明:
6 丸め処理を用いてキャッシュヒット率を上げることによる計算時間の削減効果を検証します。
7関連リンク:
8 lru_cache_benchmark_usage
9"""
10
11from __future__ import annotations
12
13import argparse
14from functools import lru_cache
15import math
16import random
17import statistics
18import time
19
20
21# 実際に重い関数本体が呼ばれた回数を数える。
22plain_evaluations = 0
23cached_evaluations = 0
24
25
26def costly_exp_plain(x: float, n_exp: int) -> float:
27 """
28 概要:
29 キャッシュなし版の重い関数です。
30 詳細説明:
31 math.exp を指定回数呼び出し、実行に時間がかかる関数をシミュレートします。
32 実行のたびに plain_evaluations がインクリメントされます。
33 引数:
34 :param x: 計算対象の入力値。
35 :type x: float
36 :param n_exp: expを呼び出す回数。
37 :type n_exp: int
38 戻り値:
39 :returns: 最後に計算した exp の結果。
40 :rtype: float
41 """
42 global plain_evaluations
43 plain_evaluations += 1
44 y = 0.0
45 for _ in range(n_exp):
46 y = math.exp(x)
47 return y
48
49
50@lru_cache(maxsize=None)
51def costly_exp_cached(x_rounded: float, n_exp: int) -> float:
52 """
53 概要:
54 丸め済み引数をキーにするキャッシュ版の重い関数本体です。
55 詳細説明:
56 math.exp を指定回数呼び出します。キャッシュミスが発生したときのみ実行され、
57 その際に cached_evaluations がインクリメントされます。
58 引数:
59 :param x_rounded: 丸め済みの入力値。
60 :type x_rounded: float
61 :param n_exp: expを呼び出す回数。
62 :type n_exp: int
63 戻り値:
64 :returns: 最後に計算した exp の結果。
65 :rtype: float
66 """
67 global cached_evaluations
68 cached_evaluations += 1
69 y = 0.0
70 for _ in range(n_exp):
71 y = math.exp(x_rounded)
72 return y
73
74
75def f_with_cache(x: float, decimals: int, n_exp: int) -> float:
76 """
77 概要:
78 入力を丸めてからキャッシュ付き関数を呼び出します。
79 詳細説明:
80 小数第 decimals 位へ丸めた値をキーにして costly_exp_cached を実行し、
81 キャッシュのヒット率を高めます。
82 引数:
83 :param x: 元の入力値。
84 :type x: float
85 :param decimals: 丸める小数点以下の桁数。
86 :type decimals: int
87 :param n_exp: 重い関数内でexpを呼び出す回数。
88 :type n_exp: int
89 戻り値:
90 :returns: キャッシュ付き関数の計算結果。
91 :rtype: float
92 """
93 return costly_exp_cached(round(x, decimals), n_exp)
94
95
96def median_time(func, xs: list[float], repeat: int) -> tuple[float, float]:
97 """
98 概要:
99 関数を各入力値に適用した実行時間の中央値と合計値を計算します。
100 詳細説明:
101 指定された関数を配列の各要素に対して実行する処理を repeat 回繰り返し、
102 各試行にかかった時間の中央値を求めます。
103 引数:
104 :param func: 測定対象の関数。
105 :type func: callable
106 :param xs: 入力値のリスト。
107 :type xs: list[float]
108 :param repeat: 時間測定の繰り返し回数。
109 :type repeat: int
110 戻り値:
111 :returns: 実行時間の中央値と計算結果の合計値のタプル。
112 :rtype: tuple[float, float]
113 """
114 elapsed = []
115 checksum = 0.0
116 for _ in range(repeat):
117 total = 0.0
118 t0 = time.perf_counter()
119 for x in xs:
120 total += func(x)
121 elapsed.append(time.perf_counter() - t0)
122 checksum = total
123 return statistics.median(elapsed), checksum
124
125
126def main() -> None:
127 """
128 概要:
129 ベンチマークスクリプトのメインルーチンです。
130 詳細説明:
131 コマンドライン引数を解析し、乱数による入力データを生成した上で、
132 キャッシュの有無による実行時間の違いを測定し標準出力へ結果を表示します。
133 戻り値:
134 :returns: 戻り値はありません。
135 :rtype: None
136 """
137 parser = argparse.ArgumentParser(
138 description="丸めた引数に lru_cache を使う効果を測定します。"
139 )
140 parser.add_argument("-n", "--n", type=int, default=100_000,
141 help="[0, 1] 一様乱数の個数 (default: 100000)")
142 parser.add_argument("--decimals", type=int, default=3,
143 help="キャッシュキーへ使う小数点以下桁数 (default: 3)")
144 parser.add_argument("--n-exp", type=int, default=100,
145 help="1回の本体計算で呼ぶ exp(x) の回数 (default: 100)")
146 parser.add_argument("-r", "--repeat", type=int, default=3,
147 help="時間測定の繰り返し回数 (default: 3)")
148 parser.add_argument("--seed", type=int, default=12345,
149 help="乱数シード (default: 12345)")
150 args = parser.parse_args()
151
152 if args.n <= 0 or args.repeat <= 0 or args.n_exp <= 0 or args.decimals < 0:
153 parser.error("n, repeat, n-exp は正、decimals は 0 以上にしてください。")
154
155 rng = random.Random(args.seed)
156 xs = [rng.random() for _ in range(args.n)]
157
158 global plain_evaluations, cached_evaluations
159 plain_evaluations = 0
160 t_plain, sum_plain = median_time(
161 lambda x: costly_exp_plain(x, args.n_exp), xs, args.repeat
162 )
163
164 # 各測定を「空のキャッシュ」から始める。こうすると、繰り返し測定でも
165 # キャッシュ構築を含む公平な時間比較になる。
166 cached_evaluations = 0
167 cached_elapsed = []
168 sum_cached = 0.0
169 info = None
170 for _ in range(args.repeat):
171 costly_exp_cached.cache_clear()
172 total = 0.0
173 t0 = time.perf_counter()
174 for x in xs:
175 total += f_with_cache(x, args.decimals, args.n_exp)
176 cached_elapsed.append(time.perf_counter() - t0)
177 sum_cached = total
178 info = costly_exp_cached.cache_info()
179 t_cached = statistics.median(cached_elapsed)
180
181 print(f"N={args.n:,}, repeat={args.repeat}, exp calls per evaluation={args.n_exp}")
182 print(f"cache key: round(x, {args.decimals})")
183 print()
184 print("case requests actual evaluations median time")
185 print("-" * 72)
186 print(f"no cache {args.n * args.repeat:10,} {plain_evaluations:17,} {t_plain:11.6f} s")
187 print(f"lru_cache + rounded key {args.n * args.repeat:10,} {cached_evaluations:17,} {t_cached:11.6f} s")
188 print()
189 print(f"lru_cache info (one run): hits={info.hits:,}, misses={info.misses:,}, currsize={info.currsize:,}")
190 print(f"speedup (median): {t_plain / t_cached:.2f} x")
191 print(f"checksums (not physically meaningful): {sum_plain:.6g}, {sum_cached:.6g}")
192
193
194if __name__ == "__main__":
195 main()