execution_time/
lib.rs

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
mod time;
mod traits;

pub use self::{time::*, traits::*};
use std::time::Instant;

// Constant for the number of decimal places to use when formatting seconds
const DECIMAL: usize = 4;

/// Measures the execution time of a code block.
///
/// This struct provides methods to start a timer and print the elapsed time
/// in a user-friendly format.
pub struct ExecutionTime {
    start_time: Instant,
}

impl ExecutionTime {
    /// Starts a new stopwatch.
    ///
    /// This function initializes the timer by recording the current time.
    ///
    /// # Returns
    ///
    /// A new `ExecutionTime` instance.
    pub fn start() -> Self {
        Self {
            start_time: Instant::now(),
        }
    }

    /// Splits the total elapsed seconds into days, hours, minutes, and seconds.
    ///
    /// This method takes a floating-point number of seconds and breaks it down
    /// into human-readable units (days, hours, minutes, and seconds).
    ///
    /// # Arguments
    ///
    /// * `total_seconds` - The total elapsed time in seconds.
    ///
    /// # Returns
    ///
    /// A `Time` struct containing the split time values.
    fn split_time(&self, total_seconds: f64) -> Time {
        // Constants for seconds in a day and an hour to improve readability
        const SECONDS_IN_DAY: f64 = 86400.0;
        const SECONDS_IN_HOUR: f64 = 3600.0;
        const SECONDS_IN_MINUTE: f64 = 60.0;

        let remaining_day = total_seconds % SECONDS_IN_DAY;
        let remaining_hour = remaining_day % SECONDS_IN_HOUR;

        let days = (total_seconds / SECONDS_IN_DAY).floor() as u64;
        let hours = (remaining_day / SECONDS_IN_HOUR).floor() as u8;
        let minutes = (remaining_hour / SECONDS_IN_MINUTE).floor() as u8;
        let seconds = (remaining_hour % SECONDS_IN_MINUTE).round_float(DECIMAL);

        Time {
            days,
            hours,
            minutes,
            seconds,
        }
    }

    /// Calculates the elapsed time since the stopwatch was started.
    ///
    /// This method calculates the elapsed time, formats it into a readable string.
    ///
    /// The output format depends on whether the elapsed time is less than or
    /// greater than 60 seconds.
    pub fn get_elapsed_time(&self) -> String {
        let total_seconds = self.start_time.elapsed().as_secs_f64();
        let time_total = total_seconds.format_unit(DECIMAL, "second", "seconds");

        // Format the output based on whether the elapsed time is greater than or equal to 60 seconds
        if total_seconds >= 60.0 {
            let time_dhms = self.split_time(total_seconds).format_time();
            format!("{time_dhms} ({time_total})")
        } else {
            time_total
        }
    }

    /// Calculates and prints the elapsed time since the stopwatch was started.
    ///
    /// This method calculates the elapsed time, formats it into a readable string,
    /// and prints it to the console.
    ///
    /// The output format depends on whether the elapsed time is less than or
    /// greater than 60 seconds.
    pub fn print_elapsed_time(&self) {
        println!("Elapsed time: {}", self.get_elapsed_time());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    type Error = Box<dyn std::error::Error>;

    #[test]
    /// `cargo test -- --show-output elapsed_time_less_than_minute`
    fn elapsed_time_less_than_minute() -> Result<(), Error> {
        let timer = ExecutionTime::start();
        let total_seconds: f64 = 0.01516345;

        let formatted_total_seconds = "0.0152 second";

        let time_dhms = timer.split_time(total_seconds).format_time();
        let time_total = total_seconds.format_unit(DECIMAL, "second", "seconds");

        let formatted_output = if total_seconds >= 60.0 {
            format!("{time_dhms} ({time_total})")
        } else {
            time_total
        };

        println!("total_seconds: {total_seconds}");
        println!("formatted_total_seconds: {formatted_total_seconds}");
        println!("formatted_output: {formatted_output}\n");

        assert_eq!(formatted_total_seconds, formatted_output);

        Ok(())
    }

    #[test]
    /// `cargo test -- --show-output elapsed_time_more_than_minute`
    fn elapsed_time_more_than_minute() -> Result<(), Error> {
        let timer = ExecutionTime::start();
        let total_seconds: f64 = 65.080012345;

        let formatted_total_seconds = "1 minute, 5.0800 seconds (65.0800 seconds)";

        let time_dhms = timer.split_time(total_seconds).format_time();
        let time_total = total_seconds.format_unit(DECIMAL, "second", "seconds");

        let formatted_output = if total_seconds >= 60.0 {
            format!("{time_dhms} ({time_total})")
        } else {
            time_total
        };

        println!("total_seconds: {total_seconds}");
        println!("formatted_total_seconds: {formatted_total_seconds}");
        println!("formatted_output: {formatted_output}\n");

        assert_eq!(formatted_total_seconds, formatted_output);

        Ok(())
    }

    #[test]
    /// `cargo test -- --show-output elapsed_time_more_than_hour`
    fn elapsed_time_more_than_hour() -> Result<(), Error> {
        let timer = ExecutionTime::start();
        let total_seconds: f64 = 3700.05689123;

        let formatted_total_seconds = "1 hour, 1 minute, 40.0569 seconds (3700.0569 seconds)";

        let time_dhms = timer.split_time(total_seconds).format_time();
        let time_total = total_seconds.format_unit(DECIMAL, "second", "seconds");

        let formatted_output = if total_seconds >= 60.0 {
            format!("{time_dhms} ({time_total})")
        } else {
            time_total
        };

        println!("total_seconds: {total_seconds}");
        println!("formatted_total_seconds: {formatted_total_seconds}");
        println!("formatted_output: {formatted_output}\n");

        assert_eq!(formatted_total_seconds, formatted_output);

        Ok(())
    }

    #[test]
    /// `cargo test -- --show-output elapsed_time_more_than_day`
    fn elapsed_time_more_than_day() -> Result<(), Error> {
        let timer = ExecutionTime::start();
        let total_seconds: f64 = 86400.0 + 3700.03;

        let formatted_total_seconds =
            "1 day, 1 hour, 1 minute, 40.0300 seconds (90100.0300 seconds)";

        let time_dhms = timer.split_time(total_seconds).format_time();
        let time_total = total_seconds.format_unit(DECIMAL, "second", "seconds");

        let formatted_output = if total_seconds >= 60.0 {
            format!("{time_dhms} ({time_total})")
        } else {
            time_total
        };

        println!("total_seconds: {total_seconds}");
        println!("formatted_total_seconds: {formatted_total_seconds}");
        println!("formatted_output: {formatted_output}\n");

        assert_eq!(formatted_total_seconds, formatted_output);

        Ok(())
    }
}