1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
//! Measures time taken by single phases of the compiler.
//!
//! This is especially useful to detect problems in optimization
//! routines.
//!
//! This is NOT an utility that should be used for benchmarking!
//! Benchmarking involves running a program multiple times with
//! warm up phases and median/avg/stddev of measurements.

use std::{
    fmt,
    fs::File,
    sync::Mutex,
    time::{Duration, Instant},
}; // TODO: more precise clock

lazy_static::lazy_static! {
    static ref TIMINGS: Mutex<Timings> = { Mutex::new(Timings { measurements: Vec::new()}) };
}

#[derive(Debug, Clone)]
pub struct Measurement {
    start: Instant,
    label: String,
}

impl Measurement {
    pub fn start(label: &str) -> Self {
        Self {
            start: Instant::now(),
            label: label.to_string(),
        }
    }

    pub fn stop(&self) {
        let measurement = CompletedMeasurement {
            label: self.label.clone(),
            start: self.start,
            stop: Instant::now(),
        };
        TIMINGS.lock().unwrap().measurements.push(measurement);
    }

    pub fn guard(label: &str) -> MeasurementGuard {
        MeasurementGuard(Self::start(label))
    }
}

pub struct MeasurementGuard(Measurement);

impl Drop for MeasurementGuard {
    fn drop(&mut self) {
        self.0.stop();
    }
}

#[macro_export]
macro_rules! timed_scope {
    ($label:expr) => {
        let measurement = ::compiler_shared::timing::Measurement::guard($label);
    };
}

#[derive(Debug, Clone)]
struct CompletedMeasurement {
    start: Instant,
    stop: Instant,
    label: String,
}

impl CompletedMeasurement {
    fn duration(&self) -> Duration {
        self.stop.duration_since(self.start)
    }
}

#[derive(Debug, Clone)]
struct Timings {
    measurements: Vec<CompletedMeasurement>,
}

impl fmt::Display for Timings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        AsciiDisp(&CompilerMeasurements::from(self.clone())).fmt(f)
    }
}

impl<'a> fmt::Display for AsciiDisp<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let min_label_width = 50;

        for timing in self.0 {
            let indent = "  ".repeat(timing.indent);

            writeln!(
                f,
                "{nesting}{: <label_width$}    {: >ms_width$}ms",
                timing.label,
                timing.duration.as_millis(),
                nesting = indent,
                label_width = min_label_width - indent.len(),
                ms_width = 6
            )?;
        }

        Ok(())
    }
}

pub fn print() {
    if std::env::var("MEASURE_STDERR").is_ok() {
        eprintln!("Performance Analysis");
        eprintln!("====================\n");

        if cfg!(feature = "debugger_gui") {
            eprintln!("Measurements not available with enabled breakpoints");
        } else {
            eprintln!("{}", TIMINGS.lock().unwrap());
        }
    }

    if let Ok(path) = std::env::var("MEASURE_JSON") {
        let file = File::create(path).unwrap();
        serde_json::to_writer(
            file,
            &CompilerMeasurements::from(TIMINGS.lock().unwrap().clone()),
        )
        .unwrap();
    }
}

// Frozen and completed measurements that can be serialized
pub type CompilerMeasurements = Vec<SingleMeasurement>;
pub struct AsciiDisp<'a>(pub &'a CompilerMeasurements);

impl From<Timings> for CompilerMeasurements {
    fn from(measurements: Timings) -> Self {
        let mut frozen = vec![];
        let mut active = vec![];

        let mut listing = measurements.measurements.clone();
        listing.sort_by(|a, b| a.start.cmp(&b.start));

        for timing in listing.into_iter() {
            active.retain(|measurement: &CompletedMeasurement| measurement.stop > timing.start);

            frozen.push(SingleMeasurement {
                label: timing.label.clone(),
                indent: active.len(),
                duration: timing.duration(),
            });

            active.push(timing);
        }

        frozen
    }
}

#[derive(Debug, Clone, serde_derive::Serialize, serde_derive::Deserialize)]
pub struct SingleMeasurement {
    pub label: String,
    pub indent: usize,
    pub duration: Duration,
}