use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
pub const SPLIT: usize = 0;
pub const VALIDATE: usize = 1;
pub const PARSE: usize = 2;
pub const EXPORT: usize = 3;
pub const MERGE: usize = 4;
pub const COUNT: usize = 5;
pub const NAMES: [&str; COUNT] = ["split", "validate", "parse", "export", "merge"];
static ENABLED: AtomicBool = AtomicBool::new(false);
static NANOS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
static CALLS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
#[inline]
pub fn enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
pub fn reset() {
for i in 0..COUNT {
NANOS[i].store(0, Ordering::Relaxed);
CALLS[i].store(0, Ordering::Relaxed);
}
ENABLED.store(true, Ordering::Relaxed);
}
pub fn disable() {
ENABLED.store(false, Ordering::Relaxed);
}
#[inline]
pub fn add(stage: usize, nanos: u64) {
if enabled() {
NANOS[stage].fetch_add(nanos, Ordering::Relaxed);
CALLS[stage].fetch_add(1, Ordering::Relaxed);
}
}
pub fn snapshot() -> Vec<(&'static str, u64, u64)> {
(0..COUNT)
.map(|i| {
(
NAMES[i],
NANOS[i].load(Ordering::Relaxed),
CALLS[i].load(Ordering::Relaxed),
)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counters_accumulate_only_while_enabled() {
disable();
add(PARSE, 100);
assert_eq!(snapshot()[PARSE].1, 0, "no accounting while disabled");
reset();
add(PARSE, 5);
add(PARSE, 7);
let s = snapshot();
assert_eq!(s[PARSE].1, 12);
assert_eq!(s[PARSE].2, 2);
assert_eq!(s[SPLIT].1, 0);
disable();
}
}