use crate::registry::{find_benchmark, list_benchmark_names};
use crate::timing::BenchSpec;
use crate::types::{BenchError, RunnerReport};
pub fn run_benchmark(spec: BenchSpec) -> Result<RunnerReport, BenchError> {
let bench_fn = find_benchmark(&spec.name).ok_or_else(|| {
let available = list_benchmark_names()
.into_iter()
.map(String::from)
.collect();
BenchError::UnknownFunction(spec.name.clone(), available)
})?;
let report = (bench_fn.runner)(spec)?;
Ok(report)
}
#[derive(Debug, Clone)]
pub struct BenchmarkBuilder {
function: String,
iterations: u32,
warmup: u32,
}
impl BenchmarkBuilder {
pub fn new(function: impl Into<String>) -> Self {
Self {
function: function.into(),
iterations: 100, warmup: 10, }
}
pub fn iterations(mut self, n: u32) -> Self {
self.iterations = n;
self
}
pub fn warmup(mut self, n: u32) -> Self {
self.warmup = n;
self
}
pub fn run(self) -> Result<RunnerReport, BenchError> {
let spec = BenchSpec {
name: self.function,
iterations: self.iterations,
warmup: self.warmup,
};
run_benchmark(spec)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_defaults() {
let builder = BenchmarkBuilder::new("test_fn");
assert_eq!(builder.iterations, 100);
assert_eq!(builder.warmup, 10);
}
#[test]
fn test_builder_customization() {
let builder = BenchmarkBuilder::new("test_fn").iterations(50).warmup(5);
assert_eq!(builder.iterations, 50);
assert_eq!(builder.warmup, 5);
}
}