File size: 1,544 Bytes
dbb04e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""

Benchmark BinaryHDV.permute() using the production implementation.

"""

import sys
import timeit
from pathlib import Path
from typing import Dict, List

import numpy as np

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from mnemocore.core.binary_hdv import BinaryHDV


def permute_reference(data: np.ndarray, shift: int) -> np.ndarray:
    bits = np.unpackbits(data)
    bits = np.roll(bits, shift)
    return np.packbits(bits)


def benchmark_dimension(dimension: int, shift: int = 13) -> Dict[str, float]:
    hdv = BinaryHDV.random(dimension)

    # Correctness check against golden reference
    expected = permute_reference(hdv.data, shift)
    actual = hdv.permute(shift).data
    assert np.array_equal(actual, expected), "permute() mismatch vs reference"

    t = min(
        timeit.repeat(
            stmt="hdv.permute(shift)",
            globals={"hdv": hdv, "shift": shift},
            repeat=5,
            number=500,
        )
    )
    us = (t / 500) * 1_000_000
    return {"dimension": float(dimension), "permute_us": us}


def main() -> None:
    dimensions: List[int] = [512, 4096, 16384, 32768, 65536, 131072]
    print("BinaryHDV.permute() benchmark (production path)")
    print(f"{'Dimension':>10} | {'permute(us)':>12}")
    print("-" * 27)
    for dim in dimensions:
        result = benchmark_dimension(dim)
        print(f"{int(result['dimension']):>10} | {result['permute_us']:>12.2f}")


if __name__ == "__main__":
    main()