swc_ecma_minifier/
timing.rs

1use std::{
2    io::{self, Write},
3    time::{Duration, Instant},
4};
5
6use crate::util::now;
7
8/// TOOD: Add timings.
9#[derive(Default, Debug)]
10pub struct Timings {
11    current_section: Option<(String, Instant)>,
12    entries: Vec<(String, Duration)>,
13}
14
15impl Timings {
16    pub fn new() -> Timings {
17        Default::default()
18    }
19
20    pub fn section(&mut self, name: &str) {
21        self.end_section();
22
23        self.current_section = now().map(|now| (String::from(name), now));
24    }
25
26    pub fn end_section(&mut self) {
27        if let Some((prev_name, prev_start)) = &self.current_section {
28            self.entries.push((
29                prev_name.clone(),
30                Instant::now().duration_since(*prev_start),
31            ));
32        }
33    }
34
35    pub fn log(&mut self) {
36        self.end_section();
37
38        let entries_printout: Vec<u8> = self
39            .entries
40            .iter()
41            .flat_map(|(name, duration)| {
42                let sec_duration = duration.as_micros() / 1_000_000;
43
44                format!("- {}: {:.6}s\n", name, sec_duration).into_bytes()
45            })
46            .collect();
47
48        io::stderr()
49            .write_all(&entries_printout)
50            .expect("Could not write timings");
51
52        *self = Timings::new();
53    }
54}