use std::time::{Duration, Instant};
use std::collections::HashMap;
#[derive(Debug, Default)]
pub struct PerformanceMonitor {
start_times: HashMap<String, Instant>,
durations: HashMap<String, Duration>,
}
impl PerformanceMonitor {
pub fn new() -> Self {
Self::default()
}
pub fn start(&mut self, stage: &str) {
self.start_times.insert(stage.to_string(), Instant::now());
}
pub fn stop(&mut self, stage: &str) {
if let Some(start_time) = self.start_times.remove(stage) {
let duration = start_time.elapsed();
self.durations.insert(stage.to_string(), duration);
}
}
pub fn get_duration(&self, stage: &str) -> Option<&Duration> {
self.durations.get(stage)
}
pub fn get_durations(&self) -> &HashMap<String, Duration> {
&self.durations
}
pub fn reset(&mut self) {
self.start_times.clear();
self.durations.clear();
}
pub fn print_report(&self) {
println!("Performance Report:");
println!("==================");
for (stage, duration) in self.durations.iter() {
println!("{}: {:?}", stage, duration);
}
println!("==================");
}
}
pub struct PerformanceGuard<'a> {
monitor: &'a mut PerformanceMonitor,
stage: String,
}
impl<'a> PerformanceGuard<'a> {
pub fn new(monitor: &'a mut PerformanceMonitor, stage: &str) -> Self {
monitor.start(stage);
Self {
monitor,
stage: stage.to_string(),
}
}
}
impl<'a> Drop for PerformanceGuard<'a> {
fn drop(&mut self) {
self.monitor.stop(&self.stage);
}
}