use std::time::{Duration, Instant};
pub fn timeit<F, R, T>(f: F, t: T) -> R
where
F: FnOnce() -> R,
T: FnOnce(Duration)
{
let start = Instant::now();
let ret = f();
let dur = start.elapsed();
t(dur);
ret
}
pub struct TimeIt<'a> {
start: Instant,
action: &'a str,
#[allow(clippy::type_complexity)]
cb: Option<Box<dyn FnOnce(&str, Duration) + Send>>
}
impl<'a> TimeIt<'a> {
pub fn new(
action: &'a str,
cb: impl FnOnce(&str, Duration) + Send + 'static
) -> Self {
Self {
start: Instant::now(),
action,
cb: Some(Box::new(cb))
}
}
}
impl Drop for TimeIt<'_> {
fn drop(&mut self) {
let dur = self.start.elapsed();
let Some(cb) = self.cb.take() else { return };
cb(self.action, dur);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tmit() {
let _tmit = TimeIt::new("initialize", |action, dur| {
println!("{action} took {dur:?}");
});
}
}