use std::time::Instant;
const BLOCK: usize = 16;
pub(crate) const TICK_STRIDE: usize = 64;
const WARM: f64 = 8.0;
const WARM_GAIN: f64 = 0.3;
#[derive(Clone, Default, serde::Deserialize, serde::Serialize)]
pub(crate) struct Cost {
block_n: usize,
block_min: f64,
ema: f64,
weight: f64,
prev_y: Option<f64>,
prev_d: Option<f64>,
nd: f64,
sum_d: f64,
sum_d2: f64,
ndd: f64,
sum_dd: f64,
}
impl Cost {
pub(crate) fn sample(&mut self, ns: f64) {
self.block_min = if self.block_n == 0 { ns } else { self.block_min.min(ns) };
self.block_n += 1;
if self.block_n < BLOCK {
return;
}
self.block_n = 0;
let y = self.block_min;
if let Some(p) = self.prev_y {
let d = y - p;
self.nd += 1.0;
self.sum_d += d;
self.sum_d2 += d * d;
if let Some(pd) = self.prev_d {
self.ndd += 1.0;
self.sum_dd += d * pd;
}
self.prev_d = Some(d);
}
self.prev_y = Some(y);
let a = self.gain();
self.ema += a * (y - self.ema);
self.weight += a * (1.0 - self.weight);
}
pub(crate) fn ns(&self) -> Option<f64> {
(self.weight > 0.0).then(|| self.ema / self.weight)
}
fn gain(&self) -> f64 {
if self.ndd < WARM {
return WARM_GAIN;
}
let mean = self.sum_d / self.nd;
let var = (self.sum_d2 / self.nd - mean * mean).max(0.0);
let cov = self.sum_dd / self.ndd - mean * mean;
if cov >= 0.0 {
return 1.0;
}
let lambda = (var + 2.0 * cov).max(0.0) / -cov;
let a = (-lambda + (lambda * lambda + 4.0 * lambda).sqrt()) / 2.0;
a.max(1.0 / self.nd.max(1.0))
}
}
pub(crate) struct Clock(Instant);
impl Clock {
pub(crate) fn new() -> Self {
Clock(Instant::now())
}
pub(crate) fn mark(&mut self, now: Instant) -> f64 {
let ns = now.duration_since(self.0).as_nanos() as f64;
self.0 = now;
ns
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_level_is_the_floor_not_the_mean() {
let mut c = Cost::default();
let mut state = 12_345u64;
let mut rand = || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(state >> 33) as f64 / (1u64 << 31) as f64
};
let mut raw = Vec::new();
for _ in 0..BLOCK * 400 {
let s = if rand() < 0.1 { 100.0 + 5_000.0 * rand() } else { 100.0 + 20.0 * rand() };
raw.push(s);
c.sample(s);
}
let mean = raw.iter().sum::<f64>() / raw.len() as f64;
let got = c.ns().expect("400 blocks closed");
assert!(got > 90.0 && got < 140.0, "estimate {got} is not the ~100ns floor");
assert!(mean > 300.0, "the tail must be there for the test to mean anything: mean {mean}");
}
#[test]
fn a_cold_start_is_not_biased_toward_zero() {
let mut c = Cost::default();
assert!(c.ns().is_none(), "no estimate before the first block closes");
for _ in 0..BLOCK {
c.sample(500.0);
}
assert_eq!(c.ns(), Some(500.0));
}
}