import time
import importlib

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def run_bench(fn, repeat=3):
    """
    Runs fn() several times and returns the fastest result.
    """
    return min(fn() for _ in range(repeat))


# ---------------------------------------------------------------------------
# Benchmarks
# ---------------------------------------------------------------------------

def cpu_loop():
    N = 80_000_000
    x = 0
    start = time.perf_counter()
    for i in range(N):
        x += (i * 3) & 7
    return time.perf_counter() - start


def list_allocation():
    N = 8_000_000
    start = time.perf_counter()
    lst = [i for i in range(N)] #noqa 841
    return time.perf_counter() - start


def function_calls():
    def f(a, b):
        return (a + b) % 17

    N = 20_000_000
    x = 0
    start = time.perf_counter()
    for i in range(N):
        x = f(x, i)
    return time.perf_counter() - start


def dict_ops():
    N = 2_000_000
    start = time.perf_counter()
    d = {}
    for i in range(N):
        d[i] = i
    for i in range(N):
        _ = d[i]
    return time.perf_counter() - start


def module_imports():
    modules = [
        'math', 'json', 're', 'statistics', 'itertools',
        'asyncio', 'pathlib', 'collections', 'urllib.request'
    ]
    start = time.perf_counter()
    for m in modules:
        importlib.reload(importlib.import_module(m))
    return time.perf_counter() - start


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def fmt(name, value):
    print(f'{name:<40} {value:.6f} seconds')

if __name__ == '__main__':
    fmt('CPU (arithmetic tight loop):', run_bench(cpu_loop))
    fmt('List allocation:', run_bench(list_allocation))
    fmt('Function calls:', run_bench(function_calls))
    fmt('Dict operations:', run_bench(dict_ops))
    fmt('Module imports:', run_bench(module_imports))
