#!/usr/bin/env python3
"""lru_cache のヒット数・実計算回数・実行時間を比較するベンチマーク。"""

from __future__ import annotations

import argparse
from functools import lru_cache
import math
import random
import statistics
import time


# 実際に重い関数本体が呼ばれた回数を数える。
plain_evaluations = 0
cached_evaluations = 0


def costly_exp_plain(x: float, n_exp: int) -> float:
    """キャッシュなし版。math.exp(x) を n_exp 回呼び出す。"""
    global plain_evaluations
    plain_evaluations += 1
    y = 0.0
    for _ in range(n_exp):
        y = math.exp(x)
    return y


@lru_cache(maxsize=None)
def costly_exp_cached(x_rounded: float, n_exp: int) -> float:
    """丸め済み引数をキーにするキャッシュ版の重い本体。"""
    global cached_evaluations
    cached_evaluations += 1
    y = 0.0
    for _ in range(n_exp):
        y = math.exp(x_rounded)
    return y


def f_with_cache(x: float, decimals: int, n_exp: int) -> float:
    """入力を小数第 decimals 位へ丸めてからキャッシュを参照する。"""
    return costly_exp_cached(round(x, decimals), n_exp)


def median_time(func, xs: list[float], repeat: int) -> tuple[float, float]:
    """func を各 x に適用した時間の median と、結果確認用の和を返す。"""
    elapsed = []
    checksum = 0.0
    for _ in range(repeat):
        total = 0.0
        t0 = time.perf_counter()
        for x in xs:
            total += func(x)
        elapsed.append(time.perf_counter() - t0)
        checksum = total
    return statistics.median(elapsed), checksum


def main() -> None:
    parser = argparse.ArgumentParser(
        description="丸めた引数に lru_cache を使う効果を測定します。"
    )
    parser.add_argument("-n", "--n", type=int, default=100_000,
                        help="[0, 1] 一様乱数の個数 (default: 100000)")
    parser.add_argument("--decimals", type=int, default=3,
                        help="キャッシュキーへ使う小数点以下桁数 (default: 3)")
    parser.add_argument("--n-exp", type=int, default=100,
                        help="1回の本体計算で呼ぶ exp(x) の回数 (default: 100)")
    parser.add_argument("-r", "--repeat", type=int, default=3,
                        help="時間測定の繰り返し回数 (default: 3)")
    parser.add_argument("--seed", type=int, default=12345,
                        help="乱数シード (default: 12345)")
    args = parser.parse_args()

    if args.n <= 0 or args.repeat <= 0 or args.n_exp <= 0 or args.decimals < 0:
        parser.error("n, repeat, n-exp は正、decimals は 0 以上にしてください。")

    rng = random.Random(args.seed)
    xs = [rng.random() for _ in range(args.n)]

    global plain_evaluations, cached_evaluations
    plain_evaluations = 0
    t_plain, sum_plain = median_time(
        lambda x: costly_exp_plain(x, args.n_exp), xs, args.repeat
    )

    # 各測定を「空のキャッシュ」から始める。こうすると、繰り返し測定でも
    # キャッシュ構築を含む公平な時間比較になる。
    cached_evaluations = 0
    cached_elapsed = []
    sum_cached = 0.0
    info = None
    for _ in range(args.repeat):
        costly_exp_cached.cache_clear()
        total = 0.0
        t0 = time.perf_counter()
        for x in xs:
            total += f_with_cache(x, args.decimals, args.n_exp)
        cached_elapsed.append(time.perf_counter() - t0)
        sum_cached = total
        info = costly_exp_cached.cache_info()
    t_cached = statistics.median(cached_elapsed)

    print(f"N={args.n:,}, repeat={args.repeat}, exp calls per evaluation={args.n_exp}")
    print(f"cache key: round(x, {args.decimals})")
    print()
    print("case                         requests  actual evaluations   median time")
    print("-" * 72)
    print(f"no cache                   {args.n * args.repeat:10,}  {plain_evaluations:17,}  {t_plain:11.6f} s")
    print(f"lru_cache + rounded key    {args.n * args.repeat:10,}  {cached_evaluations:17,}  {t_cached:11.6f} s")
    print()
    print(f"lru_cache info (one run): hits={info.hits:,}, misses={info.misses:,}, currsize={info.currsize:,}")
    print(f"speedup (median): {t_plain / t_cached:.2f} x")
    print(f"checksums (not physically meaningful): {sum_plain:.6g}, {sum_cached:.6g}")


if __name__ == "__main__":
    main()
