use std::sync::atomic::{compiler_fence, Ordering};
use std::time::{Duration, Instant};
pub struct PerfTimer {
start_time: Option<Instant>,
elapsed: Duration,
}
impl PerfTimer {
pub fn new() -> Self {
Self {
start_time: Some(Instant::now()),
elapsed: Duration::new(0, 0),
}
}
pub fn start(&mut self) {
compiler_fence(Ordering::SeqCst);
debug_assert!(self.start_time.is_none());
self.start_time = Some(Instant::now());
compiler_fence(Ordering::SeqCst);
}
pub fn stop(&mut self) {
compiler_fence(Ordering::SeqCst);
debug_assert!(self.start_time.is_some());
if let Some(t) = self.start_time.take() {
self.elapsed += Instant::now().duration_since(t)
}
compiler_fence(Ordering::SeqCst);
}
pub fn elapsed(&self) -> Duration {
let mut e = self.elapsed;
if let Some(t) = self.start_time.as_ref() {
e += Instant::now().duration_since(*t)
}
e
}
}
impl Default for PerfTimer {
fn default() -> Self {
Self::new()
}
}