//! Time spent per compiler phase, for `louise build --timings` and //! `louise check --timings`. //! //! Phases are recorded in the order they first run; timing the same phase //! again adds to it (parsing happens once per module, say). use std::time::{Duration, Instant}; #[derive(Clone, Debug, Default)] pub struct Timings { phases: Vec<(&'static str, Duration)>, } impl Timings { /// Run `f`, adding its duration to `phase`. pub fn time(&mut self, phase: &'static str, f: impl FnOnce() -> T) -> T { let start = Instant::now(); let result = f(); self.add(phase, start.elapsed()); result } pub fn add(&mut self, phase: &'static str, d: Duration) { match self.phases.iter_mut().find(|(p, _)| *p == phase) { Some((_, total)) => *total += d, None => self.phases.push((phase, d)), } } pub fn phases(&self) -> &[(&'static str, Duration)] { &self.phases } pub fn total(&self) -> Duration { self.phases.iter().map(|(_, d)| *d).sum() } /// One line per phase, in milliseconds, then the total. pub fn report(&self) -> String { let ms = |d: Duration| d.as_secs_f64() * 1000.0; let mut out = String::new(); for (phase, d) in self.phases.iter().chain([&("total", self.total())]) { out.push_str(&format!("{phase:<12} {:>9.1} ms\n", ms(*d))); } out } } #[cfg(test)] mod tests { use super::*; #[test] fn phases_accumulate_in_first_run_order() { let mut t = Timings::default(); t.add("parse", Duration::from_millis(2)); t.add("resolve", Duration::from_millis(1)); t.add("parse", Duration::from_millis(3)); let names: Vec<_> = t.phases().iter().map(|(p, _)| *p).collect(); assert_eq!(names, ["parse", "resolve"]); assert_eq!(t.phases()[0].1, Duration::from_millis(5)); assert_eq!(t.total(), Duration::from_millis(6)); assert!( t.report().ends_with("total 6.0 ms\n"), "{}", t.report() ); } }