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
//! The `statistic` module provides functionality to collect and display
//! statistic about a genetic algorithm application and its execution.

use crate::types::fmt::Display;
use chrono::{Duration, Local};
use std::{
    convert::From,
    fmt,
    ops::{Add, AddAssign},
};

#[derive(Clone, Copy, Eq, PartialEq)]
pub struct ProcessingTime {
    duration: Duration,
}

impl ProcessingTime {
    pub fn zero() -> Self {
        ProcessingTime {
            duration: Duration::zero(),
        }
    }

    pub fn duration(&self) -> Duration {
        self.duration
    }
}

impl From<Duration> for ProcessingTime {
    fn from(duration: Duration) -> Self {
        ProcessingTime { duration }
    }
}

impl fmt::Debug for ProcessingTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.duration, f)
    }
}

impl fmt::Display for ProcessingTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.duration, f)
    }
}

impl Display for ProcessingTime {
    fn fmt(&self) -> String {
        self.duration.fmt()
    }
}

impl Add for ProcessingTime {
    type Output = ProcessingTime;
    fn add(self, other: Self) -> Self::Output {
        ProcessingTime::from(self.duration + other.duration)
    }
}

impl AddAssign for ProcessingTime {
    fn add_assign(&mut self, other: Self) {
        self.duration = self.duration + other.duration
    }
}

pub trait TrackProcessingTime {
    fn processing_time(&self) -> ProcessingTime;
}

#[derive(Clone, Debug, PartialEq)]
pub struct TimedResult<U> {
    pub result: U,
    pub time: ProcessingTime,
}

pub fn timed<F, U>(op: F) -> TimedFn<F, U>
where
    F: FnOnce() -> U,
{
    TimedFn { function: op }
}

#[derive(Clone, Debug, PartialEq)]
pub struct TimedFn<F, U>
where
    F: FnOnce() -> U,
{
    function: F,
}

impl<F, U> TimedFn<F, U>
where
    F: FnOnce() -> U,
{
    pub fn run(self) -> TimedResult<U> {
        let started_at = Local::now();
        let result = (self.function)();
        let time = Local::now().signed_duration_since(started_at);
        TimedResult {
            result,
            time: ProcessingTime::from(time),
        }
    }
}

#[cfg(test)]
mod tests;