from time import perf_counter_ns from math import ceil def measure(operation, samples=1000, warmup=100): if samples < 1 or warmup < 0: raise ValueError("invalid sample count") for _ in range(warmup): operation() times = [] for _ in range(samples): start = perf_counter_ns() operation() times.append(perf_counter_ns() - start) times.sort() return {"samples": samples, **{f"p{p}_ns": times[ceil(p*samples/100)-1] for p in (50, 95, 99)}} if __name__ == "__main__": result = measure(lambda: sum(range(100))) assert result["samples"] == 1000 assert 0 <= result["p50_ns"] <= result["p95_ns"] <= result["p99_ns"] print(result)