6 #ifndef UTILS_UTL_TIMER_H
7 #define UTILS_UTL_TIMER_H
16 static constexpr uint64_t NSEC = 1000000000;
17 static constexpr uint64_t MSEC = 1000000;
18 static constexpr uint64_t NSEC_MILISEC = 1000000;
19 static constexpr uint64_t NSEC_MSEC = 1000;
26 constexpr
Timespec64 timespecToTimespec64(
const struct timespec& t) {
27 return {.tv_sec = t.tv_sec, .tv_nsec = t.tv_nsec};
30 template <
typename TIMESPEC>
31 constexpr uint64_t timespecToNanoS(
const TIMESPEC& time) {
32 return static_cast<uint64_t
>(time.tv_sec) * NSEC +
static_cast<uint64_t
>(time.tv_nsec);
35 template <
typename TIMESPEC>
36 constexpr uint64_t timespecToMicroS(
const TIMESPEC& time) {
37 return timespecToNanoS(time) / NSEC_MSEC;
40 template <
typename TIMESPEC>
41 constexpr uint64_t timespecToMilliS(
const TIMESPEC& time) {
42 return timespecToNanoS(time) / NSEC_MILISEC;
45 template <
typename TIMESPEC>
46 constexpr
double timespecToS(
const TIMESPEC& time) {
47 return timespecToNanoS(time) /
static_cast<double>(NSEC);
50 template <
typename TIMESPEC>
51 constexpr timespec diff(
const TIMESPEC& start,
const TIMESPEC& end) {
52 struct timespec temp {};
53 if (end.tv_nsec < start.tv_nsec) {
54 temp.tv_sec = end.tv_sec - start.tv_sec - 1;
55 temp.tv_nsec = NSEC + end.tv_nsec - start.tv_nsec;
57 temp.tv_sec = end.tv_sec - start.tv_sec;
58 temp.tv_nsec = end.tv_nsec - start.tv_nsec;
63 template <
typename TIMESPEC>
64 constexpr
void correctNSec(TIMESPEC* time_n_sec) {
65 while (
static_cast<decltype(NSEC)
>(time_n_sec->tv_nsec) >= NSEC) {
66 time_n_sec->tv_nsec -= NSEC;
71 template <
typename TIMESPEC>
72 constexpr
void incTime(TIMESPEC* time,
const TIMESPEC& duration) {
73 time->tv_sec += duration.tv_sec;
74 time->tv_nsec += duration.tv_nsec;
75 utils::correctNSec(time);
78 template <
typename TIMESPEC>
79 constexpr
void setTime(TIMESPEC* time,
const TIMESPEC& value) {
80 time->tv_sec = value.tv_sec;
81 time->tv_nsec = value.tv_nsec;
82 utils::correctNSec(time);
89 #endif // UTILS_UTL_TIMER_H