|
| 1 | +"""Benchmark default Cachier hashing against xxhash for large NumPy arrays.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import pickle |
| 7 | +import statistics |
| 8 | +import time |
| 9 | +from typing import Any, Callable, Dict, List |
| 10 | + |
| 11 | +import numpy as np |
| 12 | + |
| 13 | +from cachier.config import _default_hash_func |
| 14 | + |
| 15 | + |
| 16 | +def _xxhash_numpy_hash(args: tuple[Any, ...], kwds: dict[str, Any]) -> str: |
| 17 | + """Hash call arguments with xxhash, optimized for NumPy arrays. |
| 18 | +
|
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | + args : tuple[Any, ...] |
| 22 | + Positional arguments. |
| 23 | + kwds : dict[str, Any] |
| 24 | + Keyword arguments. |
| 25 | +
|
| 26 | + Returns |
| 27 | + ------- |
| 28 | + str |
| 29 | + xxhash hex digest. |
| 30 | +
|
| 31 | + """ |
| 32 | + import xxhash |
| 33 | + |
| 34 | + hasher = xxhash.xxh64() |
| 35 | + hasher.update(b"args") |
| 36 | + for value in args: |
| 37 | + if isinstance(value, np.ndarray): |
| 38 | + hasher.update(value.dtype.str.encode("utf-8")) |
| 39 | + hasher.update(str(value.shape).encode("utf-8")) |
| 40 | + hasher.update(value.tobytes(order="C")) |
| 41 | + else: |
| 42 | + hasher.update(pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)) |
| 43 | + |
| 44 | + hasher.update(b"kwds") |
| 45 | + for key, value in sorted(kwds.items()): |
| 46 | + hasher.update(pickle.dumps(key, protocol=pickle.HIGHEST_PROTOCOL)) |
| 47 | + if isinstance(value, np.ndarray): |
| 48 | + hasher.update(value.dtype.str.encode("utf-8")) |
| 49 | + hasher.update(str(value.shape).encode("utf-8")) |
| 50 | + hasher.update(value.tobytes(order="C")) |
| 51 | + else: |
| 52 | + hasher.update(pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)) |
| 53 | + |
| 54 | + return hasher.hexdigest() |
| 55 | + |
| 56 | + |
| 57 | +def _benchmark(hash_func: Callable[[tuple[Any, ...], dict[str, Any]], str], args: tuple[Any, ...], runs: int) -> float: |
| 58 | + durations: List[float] = [] |
| 59 | + for _ in range(runs): |
| 60 | + start = time.perf_counter() |
| 61 | + hash_func(args, {}) |
| 62 | + durations.append(time.perf_counter() - start) |
| 63 | + return statistics.median(durations) |
| 64 | + |
| 65 | + |
| 66 | +def main() -> None: |
| 67 | + """Run benchmark comparing cachier default hashing with xxhash.""" |
| 68 | + parser = argparse.ArgumentParser(description=__doc__) |
| 69 | + parser.add_argument( |
| 70 | + "--elements", |
| 71 | + type=int, |
| 72 | + default=10_000_000, |
| 73 | + help="Number of float64 elements in the benchmark array", |
| 74 | + ) |
| 75 | + parser.add_argument("--runs", type=int, default=7, help="Number of benchmark runs") |
| 76 | + parsed = parser.parse_args() |
| 77 | + |
| 78 | + try: |
| 79 | + import xxhash # noqa: F401 |
| 80 | + except ImportError as error: |
| 81 | + raise SystemExit("Missing dependency: xxhash. Install with `pip install xxhash`.") from error |
| 82 | + |
| 83 | + array = np.arange(parsed.elements, dtype=np.float64) |
| 84 | + args = (array,) |
| 85 | + |
| 86 | + results: Dict[str, float] = { |
| 87 | + "cachier_default": _benchmark(_default_hash_func, args, parsed.runs), |
| 88 | + "xxhash_reference": _benchmark(_xxhash_numpy_hash, args, parsed.runs), |
| 89 | + } |
| 90 | + |
| 91 | + ratio = results["cachier_default"] / results["xxhash_reference"] |
| 92 | + |
| 93 | + print(f"Array elements: {parsed.elements:,}") |
| 94 | + print(f"Array bytes: {array.nbytes:,}") |
| 95 | + print(f"Runs: {parsed.runs}") |
| 96 | + print(f"cachier_default median: {results['cachier_default']:.6f}s") |
| 97 | + print(f"xxhash_reference median: {results['xxhash_reference']:.6f}s") |
| 98 | + print(f"ratio (cachier_default / xxhash_reference): {ratio:.2f}x") |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == "__main__": |
| 102 | + main() |
0 commit comments