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
use std::collections::BTreeMap;
use std::fmt;
use std::time::{Duration, Instant};

/// Measures duration of round proceeding
pub struct Benchmark {
    results: BenchmarkResults,
}

impl Benchmark {
    pub fn new() -> Self {
        Self {
            results: Default::default(),
        }
    }

    pub fn start(&mut self) -> Stopwatch {
        Stopwatch {
            started_at: Instant::now(),
            b: self,
        }
    }

    fn add_measurement(&mut self, round: u16, time: Duration) {
        let m = self.results.entry(round).or_insert(Measurements {
            n: 0,
            total_time: Duration::default(),
        });
        m.n += 1;
        m.total_time += time;
    }

    pub fn results(&self) -> &BenchmarkResults {
        &self.results
    }
}

pub struct Stopwatch<'a> {
    started_at: Instant,
    b: &'a mut Benchmark,
}

impl<'a> Stopwatch<'a> {
    pub fn stop_and_save(self, round_n: u16) -> Duration {
        let time = Instant::now().duration_since(self.started_at);
        self.b.add_measurement(round_n, time);
        time
    }
}

/// Benchmark results for every particular round
pub type BenchmarkResults = BTreeMap<u16, Measurements>;

/// Benchmark results for particular round
///
/// `n` measurements took in total `total_time`
pub struct Measurements {
    pub n: u16,
    pub total_time: Duration,
}

impl fmt::Debug for Measurements {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.total_time / u32::from(self.n))
    }
}