use std::time::{Duration, Instant};
const ROUNDS: usize = 5;
const ATTEMPTS: usize = 3;
pub(crate) const LINEAR_BOUND: u32 = 8;
pub(crate) fn costs_under(small: &str, large: &str, bound: u32, scan: impl Fn(&str)) -> bool {
(0..ATTEMPTS).any(|_| {
let (small_time, large_time) = fastest_of_interleaved(small, large, &scan);
large_time < small_time * bound
})
}
fn fastest_of_interleaved(small: &str, large: &str, scan: &impl Fn(&str)) -> (Duration, Duration) {
let time = |source: &str| {
let start = Instant::now();
scan(source);
start.elapsed()
};
(0..ROUNDS).fold((Duration::MAX, Duration::MAX), |(s, l), _| {
(s.min(time(small)), l.min(time(large)))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn quadratic(source: &str) {
let n = source.len();
let mut acc = 0u64;
for i in 0..n {
for j in 0..n {
acc = acc.wrapping_add((i ^ j) as u64);
}
}
std::hint::black_box(acc);
}
fn linear(source: &str) {
let mut acc = 0u64;
for _ in 0..64 {
for b in source.bytes() {
acc = acc.wrapping_add(b as u64);
}
}
std::hint::black_box(acc);
}
#[test]
fn a_quadratic_scan_is_over_the_linear_bound() {
let small = "x".repeat(500);
let large = "x".repeat(4_000);
assert!(!costs_under(&small, &large, LINEAR_BOUND, quadratic));
}
#[test]
fn a_linear_scan_is_under_the_linear_bound() {
let small = "x".repeat(250_000);
let large = "x".repeat(1_000_000);
assert!(costs_under(&small, &large, LINEAR_BOUND, linear));
}
}