Motorcortex Core  version: 2.7.6
utl_timer.h
1 /*
2  * Developer : Alexey Zakharov (alexey.zakharov@vectioneer.com)
3  * All rights reserved. Copyright (c) 2015 VECTIONEER.
4  */
5 
6 #ifndef UTILS_UTL_TIMER_H
7 #define UTILS_UTL_TIMER_H
8 
9 #include <cstdint>
10 #include <ctime>
11 
12 namespace mcx {
13 
14 namespace utils {
15 
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;
20 
21 struct Timespec64 {
22  int64_t tv_sec; /* Seconds. */
23  int64_t tv_nsec; /* Nanoseconds. */
24 };
25 
26 constexpr Timespec64 timespecToTimespec64(const struct timespec& t) {
27  return {.tv_sec = t.tv_sec, .tv_nsec = t.tv_nsec};
28 }
29 
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);
33 }
34 
35 template <typename TIMESPEC>
36 constexpr uint64_t timespecToMicroS(const TIMESPEC& time) {
37  return timespecToNanoS(time) / NSEC_MSEC;
38 }
39 
40 template <typename TIMESPEC>
41 constexpr uint64_t timespecToMilliS(const TIMESPEC& time) {
42  return timespecToNanoS(time) / NSEC_MILISEC;
43 }
44 
45 template <typename TIMESPEC>
46 constexpr double timespecToS(const TIMESPEC& time) {
47  return timespecToNanoS(time) / static_cast<double>(NSEC);
48 }
49 
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;
56  } else {
57  temp.tv_sec = end.tv_sec - start.tv_sec;
58  temp.tv_nsec = end.tv_nsec - start.tv_nsec;
59  }
60  return temp;
61 }
62 
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;
67  time_n_sec->tv_sec++;
68  }
69 }
70 
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);
76 }
77 
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);
83 }
84 
85 } // namespace utils
86 
87 } // namespace mcx
88 
89 #endif // UTILS_UTL_TIMER_H
mcx::utils::Timespec64
Definition: utl_timer.h:21