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