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
/*
#![allow(unused_doc_comments)]
#![allow(unused_imports)]
#![allow(dead_code)]
// #[macro_use]
// mod utils;
/// # How to use
///
/// ## 1.
/// ```ignore
/// stopwatch_start!();
/// sleeps(1);
/// stopwatch_stop!();
/// ```
/// ## 2.
/// ```ignore
/// let mut stopwatch = Stopwatch::new();
/// stopwatch.start();
/// sleeps(1);
/// stopwatch.stop();
/// ```
// rust basic macro - macros.rs
use std::time::Instant;
use std::time::Duration;
use std::sync::Mutex;
lazy_static::lazy_static! {
static ref STOPWATCH: Mutex<Option<STOPWATCH>> = Mutex::new(None);
}
struct Stopwatch {
start_time: Instant,
stop_time: Instant,
}
impl Stopwatch {
pub fn new() -> Stopwatch {
println!("Stopwatch Start...");
Stopwatch {
start_time: Instant::now(),
stop_time: Instant::now(),
}
}
pub fn start(&mut self) {
self.start_time = Instant::now();
self.stop_time = self.start_time;
}
pub fn stop(&mut self) {
self.stop_time = Instant::now();
let elapsed_time = self.duration();
println!("Stopwatch Stop... Elapsed time: {:?}", elapsed_time);
}
pub fn duration(&self) -> Duration {
self.stop_time - self.start_time
}
}
#[macro_export]
macro_rules! stopwatch_start {
() => {
let stopwatch = Stopwatch::new();
*STOPWATCH.lock().unwrap() = Some(stopwatch);
};
}
#[macro_export]
macro_rules! stopwatch_stop {
() => {
let mut stopwatch_option = STOPWATCH.lock().unwrap();
if let Some(ref mut stopwatch) = *stopwatch_option {
stopwatch.stop();
}
*stopwatch_option = None;
};
}
#[test]
fn test_stopwatch() {
use std::thread;
let sleeps = |second| {
let timeout = Duration::from_secs(second);
thread::park_timeout(timeout);
};
// stopwatch_start!();
// sleeps(1);
// stopwatch_stop!();
let mut stopwatch = Stopwatch::new();
stopwatch.start();
sleeps(1);
stopwatch.stop();
}
*/