-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.cpp
More file actions
86 lines (72 loc) · 2.3 KB
/
timer.cpp
File metadata and controls
86 lines (72 loc) · 2.3 KB
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
#include <chrono>
#include <thread>
#include <iostream>
#include "types.h"
class Timer {
private:
f64 limit;
u32 count;
f64 _current;
u32 _reach_count;
public:
Timer(f64 _limit, u32 _count = 0)
: limit(_limit), count(_count), _current(0), _reach_count(_count) {}
Timer(const Timer&) = delete;
Timer& operator=(const Timer&) = delete;
Timer(Timer&&) = delete;
Timer& operator=(Timer&&) = delete;
~Timer() = default;
Timer& start() {
if (!started()) {
_current = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
_reach_count = 0;
}
return *this;
}
bool started() const {
return _current != 0;
}
f64 current() const {
if (started()) {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() - _current;
}
else {
return 0;
}
}
bool reached() {
_reach_count++;
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() - _current > limit && _reach_count > count;
}
Timer& reset() {
_current = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
_reach_count = 0;
return *this;
}
Timer& clear() {
_current = 0;
_reach_count = count;
return *this;
}
bool reached_and_reset() {
if (reached()) {
reset();
return true;
}
else {
return false;
}
}
void wait() {
f64 diff = _current + limit - std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
if (diff > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<u32>(diff)));
}
}
void show() {
std::cout << *this << std::endl;
}
friend std::ostream& operator<<(std::ostream& os, const Timer& timer) {
return os << "Timer(limit=" << timer.current() << "/" << timer.limit << ", count=" << timer._reach_count << "/" << timer.count << ")";
}
};