Skip to main content

zsfm_burn/
bench.rs

1use std::time::Instant;
2
3/// One timed op measurement: Burn time plus max abs error vs the host reference.
4pub struct OpMeasurement {
5    pub op: &'static str,
6    pub shape: &'static str,
7    pub burn_ms: f64,
8    pub max_abs_err: f32,
9}
10
11impl OpMeasurement {
12    pub fn markdown_row(&self) -> String {
13        format!(
14            "| {} | {} | {:.3} | {:.2e} |",
15            self.op, self.shape, self.burn_ms, self.max_abs_err
16        )
17    }
18}
19
20/// Time `f` over `iters` warm-started iterations, return median ms.
21pub fn bench_op(iters: usize, mut f: impl FnMut()) -> f64 {
22    f(); // warmup
23    let mut times: Vec<f64> = Vec::with_capacity(iters);
24    for _ in 0..iters {
25        let t = Instant::now();
26        f();
27        times.push(t.elapsed().as_secs_f64() * 1000.0);
28    }
29    times.sort_by(|a, b| a.total_cmp(b));
30    times[iters / 2]
31}
32
33/// Max absolute elementwise error between two f32 slices.
34pub fn max_abs_err(a: &[f32], b: &[f32]) -> f32 {
35    a.iter()
36        .zip(b.iter())
37        .map(|(x, y)| (x - y).abs())
38        .fold(0.0f32, f32::max)
39}