forked from HNUSystemsLab/ZBTree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.hpp
More file actions
76 lines (65 loc) · 1.68 KB
/
timer.hpp
File metadata and controls
76 lines (65 loc) · 1.68 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
#pragma once
#include <chrono>
#include <iostream>
#include <ratio>
#include <type_traits>
template <typename T>
struct is_duration : std::false_type {};
template <class Rep, std::intmax_t Num, std::intmax_t Denom>
struct is_duration<std::chrono::duration<Rep, std::ratio<Num, Denom>>>
: std::true_type {};
/**
* @brief Wrapper that implements stopwatch functionality.
*
*/
class Timer {
public:
Timer() noexcept {}
~Timer() noexcept {}
/**
* @brief Start time counter.
*
*/
void start() noexcept { start_ = std::chrono::high_resolution_clock::now(); }
/**
* @brief Clear time counter.
*
*/
void clear() noexcept { start_ = {}; }
/**
* @brief Returns amount of elapsed time.
*
* @tparam T unit used to return.
* @return float
*/
template <typename T>
float elapsed() noexcept {
static_assert(is_duration<T>::value);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, typename T::period> e = stop - start_;
return e.count();
}
/**
* @brief Returns true if given duration is elapsed since last call.
*
* @tparam T unit used by duration.
* @param d duration to be checked.
* @return true
* @return false
*/
template <typename T>
bool is_elapsed(const T& d) noexcept {
static_assert(is_duration<T>::value);
static auto prev = start_;
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<float, typename T::period> e = stop - prev;
if (e >= d) {
prev = stop;
return true;
} else
return false;
}
private:
/// Time point when the stopwatched started.
std::chrono::high_resolution_clock::time_point start_;
};