#!/usr/bin/env python3
"""
概要:
    lru_cache のヒット数、実計算回数、実行時間を比較するベンチマークスクリプトです。
詳細説明:
    丸め処理を用いてキャッシュヒット率を上げることによる計算時間の削減効果を検証します。
関連リンク:
    lru_cache_benchmark_usage
"""

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 を指定回数呼び出し、実行に時間がかかる関数をシミュレートします。
        実行のたびに plain_evaluations がインクリメントされます。
    引数:
        :param x: 計算対象の入力値。
        :type x: float
        :param n_exp: expを呼び出す回数。
        :type n_exp: int
    戻り値:
        :returns: 最後に計算した exp の結果。
        :rtype: float
    """
    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:
    """
    概要:
        丸め済み引数をキーにするキャッシュ版の重い関数本体です。
    詳細説明:
        math.exp を指定回数呼び出します。キャッシュミスが発生したときのみ実行され、
        その際に cached_evaluations がインクリメントされます。
    引数:
        :param x_rounded: 丸め済みの入力値。
        :type x_rounded: float
        :param n_exp: expを呼び出す回数。
        :type n_exp: int
    戻り値:
        :returns: 最後に計算した exp の結果。
        :rtype: 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 位へ丸めた値をキーにして costly_exp_cached を実行し、
        キャッシュのヒット率を高めます。
    引数:
        :param x: 元の入力値。
        :type x: float
        :param decimals: 丸める小数点以下の桁数。
        :type decimals: int
        :param n_exp: 重い関数内でexpを呼び出す回数。
        :type n_exp: int
    戻り値:
        :returns: キャッシュ付き関数の計算結果。
        :rtype: float
    """
    return costly_exp_cached(round(x, decimals), n_exp)


def median_time(func, xs: list[float], repeat: int) -> tuple[float, float]:
    """
    概要:
        関数を各入力値に適用した実行時間の中央値と合計値を計算します。
    詳細説明:
        指定された関数を配列の各要素に対して実行する処理を repeat 回繰り返し、
        各試行にかかった時間の中央値を求めます。
    引数:
        :param func: 測定対象の関数。
        :type func: callable
        :param xs: 入力値のリスト。
        :type xs: list[float]
        :param repeat: 時間測定の繰り返し回数。
        :type repeat: int
    戻り値:
        :returns: 実行時間の中央値と計算結果の合計値のタプル。
        :rtype: tuple[float, float]
    """
    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:
    """
    概要:
        ベンチマークスクリプトのメインルーチンです。
    詳細説明:
        コマンドライン引数を解析し、乱数による入力データを生成した上で、
        キャッシュの有無による実行時間の違いを測定し標準出力へ結果を表示します。
    戻り値:
        :returns: 戻り値はありません。
        :rtype: 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()