-
Notifications
You must be signed in to change notification settings - Fork 0
/
stop_watch.hpp
67 lines (64 loc) · 2.5 KB
/
stop_watch.hpp
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
#ifndef _STOP_WATCH_HPP_
#define _STOP_WATCH_HPP_
#include <chrono>
#include <utility>
#include <iostream>
#include <cassert>
class stop_watch {
std::chrono::high_resolution_clock::time_point last_time_point;
std::chrono::duration<double> time_duration;
bool is_running;
public:
stop_watch() :
last_time_point {std::chrono::high_resolution_clock::now()},
time_duration {std::chrono::duration<double>::zero()},
is_running {false}
{}
void start() {
assert(!is_running); // stop watch is already running
last_time_point = std::chrono::high_resolution_clock::now();
time_duration = std::chrono::duration<double>::zero();
is_running = true;
}
void stop() {
assert(is_running); // stop watch is not running
auto n = std::chrono::high_resolution_clock::now();
time_duration = n - last_time_point;
last_time_point = n;
is_running = false;
}
double hours() {
return std::chrono::duration_cast<std::chrono::hours>(
time_duration).count();
}
double minutes() {
return std::chrono::duration_cast<std::chrono::minutes>(
time_duration).count();
}
double seconds() {
return std::chrono::duration_cast<std::chrono::seconds>(
time_duration).count();
}
friend std::ostream& operator<<(std::ostream& out, stop_watch sw) {
std::chrono::hours h = std::chrono::duration_cast<
std::chrono::hours>(sw.time_duration);
if (h.count()) {out << h.count() << "h "; sw.time_duration -= h;}
std::chrono::minutes m = std::chrono::duration_cast<
std::chrono::minutes>(sw.time_duration);
if (m.count()) {out << m.count() << "min "; sw.time_duration -= m;}
std::chrono::seconds s = std::chrono::duration_cast<
std::chrono::seconds>(sw.time_duration);
if (s.count()) {out << s.count() << "s "; sw.time_duration -= s;}
std::chrono::milliseconds ms = std::chrono::duration_cast<
std::chrono::milliseconds>(sw.time_duration);
if (ms.count()) {out << ms.count() << "ms "; sw.time_duration -= ms;}
std::chrono::microseconds us = std::chrono::duration_cast<
std::chrono::microseconds>(sw.time_duration);
if (us.count()) {out << us.count() << "us "; sw.time_duration -= us;}
std::chrono::nanoseconds ns = std::chrono::duration_cast<
std::chrono::nanoseconds>(sw.time_duration);
if (ns.count()) {out << ns.count() << "ns "; sw.time_duration -= ns;}
return out;
}
};
#endif