| @@ -1,68 +0,0 @@ |
| 1 | | −//! Time spent per compiler phase, for `tilc build --timings`. |
| 2 | | −//! |
| 3 | | −//! Phases are recorded in the order they first run; timing the same phase |
| 4 | | −//! again adds to it (parsing happens once per module, say). |
| 5 | | − |
| 6 | | −use std::time::{Duration, Instant}; |
| 7 | | − |
| 8 | | −#[derive(Clone, Debug, Default)] |
| 9 | | −pub struct Timings { |
| 10 | | − phases: Vec<(&'static str, Duration)>, |
| 11 | | −} |
| 12 | | − |
| 13 | | −impl Timings { |
| 14 | | − /// Run `f`, adding its duration to `phase`. |
| 15 | | − pub fn time<T>(&mut self, phase: &'static str, f: impl FnOnce() -> T) -> T { |
| 16 | | − let start = Instant::now(); |
| 17 | | − let result = f(); |
| 18 | | − self.add(phase, start.elapsed()); |
| 19 | | − result |
| 20 | | − } |
| 21 | | − |
| 22 | | − pub fn add(&mut self, phase: &'static str, d: Duration) { |
| 23 | | − match self.phases.iter_mut().find(|(p, _)| *p == phase) { |
| 24 | | − Some((_, total)) => *total += d, |
| 25 | | − None => self.phases.push((phase, d)), |
| 26 | | − } |
| 27 | | − } |
| 28 | | − |
| 29 | | − pub fn phases(&self) -> &[(&'static str, Duration)] { |
| 30 | | − &self.phases |
| 31 | | − } |
| 32 | | − |
| 33 | | − pub fn total(&self) -> Duration { |
| 34 | | − self.phases.iter().map(|(_, d)| *d).sum() |
| 35 | | − } |
| 36 | | − |
| 37 | | − /// One line per phase, in milliseconds, then the total. |
| 38 | | − pub fn report(&self) -> String { |
| 39 | | − let ms = |d: Duration| d.as_secs_f64() * 1000.0; |
| 40 | | − let mut out = String::new(); |
| 41 | | − for (phase, d) in self.phases.iter().chain([&("total", self.total())]) { |
| 42 | | − out.push_str(&format!("{phase:<12} {:>9.1} ms\n", ms(*d))); |
| 43 | | − } |
| 44 | | − out |
| 45 | | − } |
| 46 | | −} |
| 47 | | − |
| 48 | | −#[cfg(test)] |
| 49 | | −mod tests { |
| 50 | | − use super::*; |
| 51 | | − |
| 52 | | − #[test] |
| 53 | | − fn phases_accumulate_in_first_run_order() { |
| 54 | | − let mut t = Timings::default(); |
| 55 | | − t.add("parse", Duration::from_millis(2)); |
| 56 | | − t.add("resolve", Duration::from_millis(1)); |
| 57 | | − t.add("parse", Duration::from_millis(3)); |
| 58 | | − let names: Vec<_> = t.phases().iter().map(|(p, _)| *p).collect(); |
| 59 | | − assert_eq!(names, ["parse", "resolve"]); |
| 60 | | − assert_eq!(t.phases()[0].1, Duration::from_millis(5)); |
| 61 | | − assert_eq!(t.total(), Duration::from_millis(6)); |
| 62 | | − assert!( |
| 63 | | − t.report().ends_with("total 6.0 ms\n"), |
| 64 | | − "{}", |
| 65 | | − t.report() |
| 66 | | − ); |
| 67 | | − } |
| 68 | | −} |