df_helper/datetime/
timer.rs

1use std::time::Instant;
2use std::time::Duration;
3
4/// 计时器
5pub struct Timer {
6    start: Instant,
7    unit: String,
8}
9
10/// 计时器
11impl Timer {
12    /// 计时开始
13    /// unit 计时单位 秒 s 毫秒 ms 微秒 us
14    pub fn start(unit: &str) -> Self {
15        Self {
16            start: Instant::now(),
17            unit: unit.to_string(),
18        }
19    }
20    /// 计时结束
21    pub fn end(&mut self, print: bool) -> u128 {
22        let duration = self.start.elapsed();
23        let data = {
24            match self.unit.as_str() {
25                "ms" => {
26                    let time = duration.as_millis();
27                    time
28                }
29                "us" => {
30                    let time = duration.as_micros();
31                    time
32                }
33                _ => {
34                    //s
35                    let time = duration.as_secs();
36                    time as u128
37                }
38            }
39        };
40        if print {
41            println!("消耗时间: {} {}", data, self.unit);
42        }
43        return data;
44    }
45    /// 暂停时间
46    /// 毫秒单位
47    pub fn sleep(ms: u64) {
48        let ten_millis = Duration::from_millis(ms);
49        std::thread::sleep(ten_millis);
50    }
51}
52