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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use howlong::*;
use std::fmt::{self, Display};
use std::fs::File;
use std::io;
use std::io::{BufWriter, Write};

use rayon::prelude::*;
use termion::{color, style};

type BenchDuration = ProcessDuration;

macro_rules! dur_gt {
    ($a: expr, $b: expr) => {
        $a.cpu_time() > $b.cpu_time()
    };
}

macro_rules! dur_div {
    ($a: expr, $b: expr) => {
        ProcessDuration {
            real: $a.real / $b,
            system: $a.system / $b,
            user: $a.user / $b,
        }
    };
}

#[derive(Debug, Clone)]
pub struct BenchVec {
    pub inner: Vec<BenchDuration>,
}

/// A struct that stores a vector of Durations for benchmarks
/// and allows some statistical operations on it
impl BenchVec {
    /// Creates a new empty BenchVec
    pub fn new() -> Self {
        Self { inner: Vec::new() }
    }

    /// Creates a BenchVec from an existing vector of Durations
    pub fn from_vec(vec: &Vec<BenchDuration>) -> Self {
        Self { inner: vec.clone() }
    }

    /// Adds an element to the BenchVec
    pub fn push(&mut self, item: BenchDuration) -> &mut Self {
        self.inner.push(item);

        self
    }

    /// Appends a different BenchVec to this one
    pub fn append(&mut self, other: Self) -> &mut Self {
        self.inner.append(&mut other.inner.clone());

        self
    }

    /// Returns the length of stored elements
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns the sum of all stored elements
    pub fn sum(&self) -> BenchDuration {
        let sum_system = self.inner.par_iter().map(|b| b.system).sum::<Duration>();
        let sum_user = self.inner.par_iter().map(|b| b.user).sum::<Duration>();
        let sum_real = self.inner.par_iter().map(|b| b.real).sum::<Duration>();

        BenchDuration {
            system: sum_system,
            user: sum_user,
            real: sum_real,
        }
    }

    /// Returns the average of all durations
    pub fn average(&self) -> BenchDuration {
        dur_div!(self.sum(), self.inner.len() as u32)
    }

    /// Returns the standard deviation of all durations
    pub fn standard_deviation(&self) -> f64 {
        (self.sum().cpu_time().as_nanos() as f64 / (self.len() as f64 - 1f64)).sqrt()
    }

    /// Compares two benchmarks by calculating the average
    pub fn compare(&self, other: Self) -> DurationDifference {
        let avg1 = self.average();
        let avg2 = other.average();
        if dur_gt!(avg1, avg2) {
            DurationDifference {
                inner: avg1 - avg2,
                positive: true,
            }
        } else {
            DurationDifference {
                inner: avg2 - avg1,
                positive: false,
            }
        }
    }
}

impl Display for BenchVec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let avg_duration = self.average();
        let standard_deviation = self.standard_deviation();
        write!(
            f,
            "{:?} (±{:.2}ns ~ {:.2}%)",
            avg_duration,
            standard_deviation,
            (standard_deviation / avg_duration.cpu_time().as_nanos() as f64) * 100f64
        )
    }
}

#[derive(Debug, Clone)]
pub struct DurationDifference {
    pub inner: BenchDuration,
    pub positive: bool,
}

impl DurationDifference {
    pub fn new(left: &BenchVec, right: &BenchVec) -> Self {
        let left_avg = left.average();
        let right_avg = right.average();
        if dur_gt!(left_avg, right_avg) {
            Self {
                inner: left_avg - right_avg,
                positive: true,
            }
        } else {
            Self {
                inner: right_avg - left_avg,
                positive: false,
            }
        }
    }
}

impl Display for DurationDifference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{:?}",
            if self.positive { "+" } else { "-" },
            self.inner
        )
    }
}

pub struct Bencher {
    measurements: Vec<BenchVec>,
    iterations: usize,
    max_auto_iterations: usize,
    writer: Option<BufWriter<File>>,
}

pub const BENCH_FILE_HEAD: &str = "name\tduration\tstandard_deviation\n";

impl Bencher {
    pub fn new() -> Self {
        Self {
            measurements: Vec::new(),
            iterations: 100,
            max_auto_iterations: 10000,
            writer: None,
        }
    }

    /// Sets the number of iterations a benchmark will be run
    /// If set to 0 it iterates until the standard deviation is below 1%
    pub fn set_iterations(&mut self, iterations: usize) -> &mut Self {
        self.iterations = iterations;

        self
    }

    pub fn set_max_iterations(&mut self, iterations: usize) -> &mut Self {
        self.max_auto_iterations = iterations;

        self
    }

    /// Benchmarks a closure a configured number of times.
    /// The result will be printed to the console with the given name.
    pub fn bench<T, F: FnMut() -> T>(&mut self, name: &str, mut func: F) -> &mut Self {
        let mut durations = BenchVec::new();
        println!(
            "\n{}{}{}{}",
            color::Fg(color::LightBlue),
            style::Bold,
            name,
            style::Reset
        );
        if self.iterations == 0 {
            let mut count = 0;
            while count < self.max_auto_iterations {
                let start = ProcessCPUClock::now();
                func();
                let duration = ProcessCPUClock::now() - start;
                durations.push(duration);

                if (durations.standard_deviation()
                    / durations.average().cpu_time().as_nanos() as f64)
                    < 0.01
                    && count > 1
                {
                    break;
                }
                count += 1;
            }
            println!("{}After {} iterations{}", style::Faint, count, style::Reset);
        } else {
            for _ in 0..self.iterations {
                let start = ProcessCPUClock::now();
                func();
                let duration = ProcessCPUClock::now() - start;
                durations.push(duration);
            }
        }
        println!("Result: {}", durations);
        if let Some(writer) = &mut self.writer {
            let _ = writer.write(
                format!(
                    "{}\t{:?}\t{:.2}ns\n",
                    name,
                    durations.average(),
                    durations.standard_deviation()
                )
                .as_bytes(),
            );
        }
        self.measurements.push(durations);

        self
    }

    /// Compares the last two benchmarks
    /// If the number of benchmarks is below 2 it doesn't do anything
    pub fn compare(&mut self) -> &mut Self {
        if self.measurements.len() > 1 {
            let left = self.measurements.get(self.measurements.len() - 1).unwrap();
            let right = self.measurements.get(self.measurements.len() - 2).unwrap();
            let diff = DurationDifference::new(left, right);
            println!("Difference: {}", diff);
        }

        self
    }

    /// Prints the settings of the Bencher
    pub fn print_settings(&mut self) -> &mut Self {
        println!(
            "\n{}{}Benchmarking Settings{}",
            color::Fg(color::Green),
            style::Underline,
            style::Reset
        );
        println!(
            "Number of iterations:\t {}",
            if self.iterations > 0 {
                self.iterations.to_string()
            } else {
                "auto".to_string()
            }
        );
        if self.iterations == 0 {
            println!("Maximum number of iterations: {}", self.max_auto_iterations)
        }

        self
    }

    /// Adds a file to write the output to
    pub fn write_output_to(&mut self, mut writer: BufWriter<File>) -> &mut Self {
        writer.write(BENCH_FILE_HEAD.as_bytes()).unwrap();
        self.writer = Some(writer);

        self
    }

    pub fn flush(&mut self) -> io::Result<()> {
        if let Some(writer) = &mut self.writer {
            writer.flush()
        } else {
            Ok(())
        }
    }
}