blob: ab64916fe45c16fe6849a99bb25fd429aea1de45 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#ifndef AOS_COMMON_TIME_H_
2#define AOS_COMMON_TIME_H_
3
4#include <stdint.h>
5#include <time.h>
brians57dd5822013-02-27 21:44:15 +00006#include <sys/time.h>
Brian4a424a22014-04-02 11:52:45 -07007#include <stdint.h>
8
9#include <type_traits>
Austin Schuh793d6b92016-05-01 13:28:14 -070010#include <chrono>
11#include <thread>
brians343bc112013-02-10 01:53:46 +000012#include <ostream>
13
brians343bc112013-02-10 01:53:46 +000014#include "aos/common/type_traits.h"
Brian Silvermanb407c672014-04-09 11:58:37 -070015#include "aos/common/macros.h"
brians343bc112013-02-10 01:53:46 +000016
17namespace aos {
Austin Schuh793d6b92016-05-01 13:28:14 -070018
19class monotonic_clock {
20 public:
21 typedef ::std::chrono::nanoseconds::rep rep;
22 typedef ::std::chrono::nanoseconds::period period;
23 typedef ::std::chrono::nanoseconds duration;
24 typedef ::std::chrono::time_point<monotonic_clock> time_point;
25
26 static monotonic_clock::time_point now() noexcept;
27 static constexpr bool is_steady = true;
28
29 // Returns the epoch (0).
30 static constexpr monotonic_clock::time_point epoch() {
Austin Schuh8aec1ed2016-05-01 13:29:20 -070031 return time_point(zero());
Austin Schuh793d6b92016-05-01 13:28:14 -070032 }
Austin Schuh8aec1ed2016-05-01 13:29:20 -070033
34 static constexpr monotonic_clock::duration zero() { return duration(0); }
Austin Schuh858c0212016-11-25 17:23:30 -080035
36 static constexpr time_point min_time{
37 time_point(duration(::std::numeric_limits<duration::rep>::min()))};
Austin Schuh793d6b92016-05-01 13:28:14 -070038};
39
brians343bc112013-02-10 01:53:46 +000040namespace time {
41
Austin Schuh6a6f90c2016-11-25 21:36:42 -080042// Enables returning the mock time value for Now instead of checking the system
43// clock.
44void EnableMockTime(monotonic_clock::time_point now);
45// Calls SetMockTime with the current actual time.
46void UpdateMockTime();
47// Sets now when time is being mocked.
48void SetMockTime(monotonic_clock::time_point now);
49// Convenience function to just increment the mock time by a certain amount in
50// a thread safe way.
51void IncrementMockTime(monotonic_clock::duration amount);
52// Disables mocking time.
53void DisableMockTime();
54
brians343bc112013-02-10 01:53:46 +000055// A nice structure for representing times.
56// 0 <= nsec_ < kNSecInSec should always be true. All functions here will make
57// sure that that is true if it was on all inputs (including *this).
58//
Brian Silverman6659bc32013-10-16 10:31:32 -070059// Negative times are supported so that all of the normal arithmetic identities
60// work. nsec_ is still always positive.
61//
brians343bc112013-02-10 01:53:46 +000062// The arithmetic and comparison operators are overloaded because they make
63// complete sense and are very useful. The default copy and assignment stuff is
Brian Silverman6659bc32013-10-16 10:31:32 -070064// left because it works fine. Multiplication of Times by Times is
brians343bc112013-02-10 01:53:46 +000065// not implemented because I can't think of any uses for them and there are
Brian Silverman6659bc32013-10-16 10:31:32 -070066// multiple ways to do it. Division of Times by Times is implemented as the
67// ratio of them. Multiplication, division, and modulus of Times by integers are
Brian Silverman0534df62014-05-26 21:19:15 -070068// implemented as interpreting the argument as nanoseconds. Modulus takes the
69// sign from the first operand.
brians343bc112013-02-10 01:53:46 +000070struct Time {
Brian Silverman52aeeac2013-08-28 16:20:53 -070071#ifdef SWIG
72// All of the uses of constexpr here can safely be simply removed.
73// NOTE: This means that relying on the fact that constexpr implicitly makes
Brian Silverman6659bc32013-10-16 10:31:32 -070074// member functions const is not valid, so they all have to be explicitly marked
75// const.
Brian Silverman52aeeac2013-08-28 16:20:53 -070076#define constexpr
77#endif // SWIG
brians343bc112013-02-10 01:53:46 +000078 public:
79 static const int32_t kNSecInSec = 1000000000;
80 static const int32_t kNSecInMSec = 1000000;
81 static const int32_t kNSecInUSec = 1000;
82 static const int32_t kMSecInSec = 1000;
83 static const int32_t kUSecInSec = 1000000;
Brian Silvermandcaa3f72015-11-29 05:32:08 +000084
85 static const Time kZero;
86
Brian Silverman92c3f1e2015-12-08 20:21:31 -050087 explicit constexpr Time(int32_t sec = 0, int32_t nsec = 0)
Brian Silverman52aeeac2013-08-28 16:20:53 -070088 : sec_(sec), nsec_(CheckConstexpr(nsec)) {
brians343bc112013-02-10 01:53:46 +000089 }
90 #ifndef SWIG
Brian Silverman52aeeac2013-08-28 16:20:53 -070091 explicit constexpr Time(const struct timespec &value)
92 : sec_(value.tv_sec), nsec_(CheckConstexpr(value.tv_nsec)) {
brians343bc112013-02-10 01:53:46 +000093 }
94 struct timespec ToTimespec() const {
95 struct timespec ans;
96 ans.tv_sec = sec_;
97 ans.tv_nsec = nsec_;
98 return ans;
99 }
Brian Silverman52aeeac2013-08-28 16:20:53 -0700100 explicit constexpr Time(const struct timeval &value)
101 : sec_(value.tv_sec), nsec_(CheckConstexpr(value.tv_usec * kNSecInUSec)) {
brians57dd5822013-02-27 21:44:15 +0000102 }
103 struct timeval ToTimeval() const {
104 struct timeval ans;
105 ans.tv_sec = sec_;
106 ans.tv_usec = nsec_ / kNSecInUSec;
107 return ans;
108 }
brians343bc112013-02-10 01:53:46 +0000109 #endif // SWIG
Brian Silverman3204dd82013-03-12 18:42:01 -0700110
Brian Silverman14fd0fb2014-01-14 21:42:01 -0800111 // CLOCK_MONOTONIC on linux and CLOCK_REALTIME on the cRIO because the
brians343bc112013-02-10 01:53:46 +0000112 // cRIO doesn't have any others.
113 // CLOCK_REALTIME is the default realtime clock and CLOCK_MONOTONIC doesn't
114 // change when somebody changes the wall clock (like the ntp deamon or
115 // whatever). See clock_gettime(2) for details.
116 //
117 // This is the clock that code that just wants to sleep for a certain amount
118 // of time or measure how long something takes should use.
119 #ifndef __VXWORKS__
120 static const clockid_t kDefaultClock = CLOCK_MONOTONIC;
121 #else
122 static const clockid_t kDefaultClock = CLOCK_REALTIME;
123 #endif
124 // Creates a Time representing the current value of the specified clock or
125 // dies.
126 static Time Now(clockid_t clock = kDefaultClock);
127
128 // Constructs a Time representing seconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700129 static constexpr Time InSeconds(double seconds) {
130 return (seconds < 0.0) ?
131 Time(static_cast<int32_t>(seconds) - 1,
132 (seconds - static_cast<int32_t>(seconds) + 1.0) * kNSecInSec) :
133 Time(static_cast<int32_t>(seconds),
134 (seconds - static_cast<int32_t>(seconds)) * kNSecInSec);
brians343bc112013-02-10 01:53:46 +0000135 }
136
137 // Constructs a time representing microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700138 static constexpr Time InNS(int64_t nseconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000139 return (nseconds < 0)
140 ? Time((nseconds - 1) / static_cast<int64_t>(kNSecInSec) - 1,
141 (((nseconds - 1) % kNSecInSec) + 1) + kNSecInSec)
142 : Time(nseconds / static_cast<int64_t>(kNSecInSec),
143 nseconds % kNSecInSec);
brians343bc112013-02-10 01:53:46 +0000144 }
145
146 // Constructs a time representing microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700147 static constexpr Time InUS(int useconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000148 return (useconds < 0)
149 ? Time((useconds + 1) / kUSecInSec - 1,
150 (((useconds + 1) % kUSecInSec) - 1) * kNSecInUSec +
151 kNSecInSec)
152 : Time(useconds / kUSecInSec,
153 (useconds % kUSecInSec) * kNSecInUSec);
brians343bc112013-02-10 01:53:46 +0000154 }
155
156 // Constructs a time representing mseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700157 static constexpr Time InMS(int mseconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000158 return (mseconds < 0)
159 ? Time((mseconds + 1) / kMSecInSec - 1,
160 (((mseconds + 1) % kMSecInSec) - 1) * kNSecInMSec +
161 kNSecInSec)
162 : Time(mseconds / kMSecInSec,
163 (mseconds % kMSecInSec) * kNSecInMSec);
164 }
165
166 // Construct a time representing the period of hertz.
Austin Schuh8aec1ed2016-05-01 13:29:20 -0700167 static constexpr ::std::chrono::nanoseconds FromRate(int hertz) {
168 return ::std::chrono::duration_cast<::std::chrono::nanoseconds>(
169 ::std::chrono::seconds(1)) /
170 hertz;
brians343bc112013-02-10 01:53:46 +0000171 }
172
173 // Checks whether or not this time is within amount nanoseconds of other.
174 bool IsWithin(const Time &other, int64_t amount) const;
175
176 // Returns the time represented all in nanoseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700177 int64_t constexpr ToNSec() const {
brians343bc112013-02-10 01:53:46 +0000178 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kNSecInSec) +
179 static_cast<int64_t>(nsec_);
180 }
181#ifdef __VXWORKS__
182 // Returns the time represented all in system clock ticks. The system clock
183 // rate is retrieved using sysClkRateGet().
184 int ToTicks() const {
185 return ToNSec() / static_cast<int64_t>(kNSecInSec / sysClkRateGet());
186 }
Brian Silverman3204dd82013-03-12 18:42:01 -0700187 // Constructs a Time representing ticks.
188 static Time InTicks(int ticks) {
Brian Silvermanffe3d712013-03-15 21:35:59 -0700189 return Time::InSeconds(static_cast<double>(ticks) / sysClkRateGet());
Brian Silverman3204dd82013-03-12 18:42:01 -0700190 }
brians343bc112013-02-10 01:53:46 +0000191#endif
192
193 // Returns the time represented in milliseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700194 int64_t constexpr ToMSec() const {
brians343bc112013-02-10 01:53:46 +0000195 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kMSecInSec) +
196 (static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInMSec));
197 }
198
Brian Silverman7645d2f2013-03-30 18:53:56 -0700199 // Returns the time represent in microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700200 int64_t constexpr ToUSec() const {
Brian Silverman7645d2f2013-03-30 18:53:56 -0700201 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kUSecInSec) +
202 (static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInUSec));
203 }
204
briansf0165ca2013-03-02 06:17:47 +0000205 // Returns the time represented in fractional seconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700206 double constexpr ToSeconds() const {
briansf0165ca2013-03-02 06:17:47 +0000207 return static_cast<double>(sec_) + static_cast<double>(nsec_) / kNSecInSec;
208 }
209
brians343bc112013-02-10 01:53:46 +0000210 #ifndef SWIG
211 Time &operator+=(const Time &rhs);
212 Time &operator-=(const Time &rhs);
213 Time &operator*=(int32_t rhs);
214 Time &operator/=(int32_t rhs);
215 Time &operator%=(int32_t rhs);
Brian Silverman0079a9d2013-10-24 15:57:35 -0700216 Time &operator%=(double rhs) = delete;
217 Time &operator*=(double rhs) = delete;
218 Time &operator/=(double rhs) = delete;
219 const Time operator*(double rhs) const = delete;
220 const Time operator/(double rhs) const = delete;
221 const Time operator%(double rhs) const = delete;
brians343bc112013-02-10 01:53:46 +0000222 #endif
223 const Time operator+(const Time &rhs) const;
224 const Time operator-(const Time &rhs) const;
225 const Time operator*(int32_t rhs) const;
226 const Time operator/(int32_t rhs) const;
Brian Silverman2e0dcfd2013-03-30 22:44:40 -0700227 double operator/(const Time &rhs) const;
brians343bc112013-02-10 01:53:46 +0000228 const Time operator%(int32_t rhs) const;
229
Brian Silverman0079a9d2013-10-24 15:57:35 -0700230 const Time operator-() const;
231
brians343bc112013-02-10 01:53:46 +0000232 bool operator==(const Time &rhs) const;
233 bool operator!=(const Time &rhs) const;
234 bool operator<(const Time &rhs) const;
235 bool operator>(const Time &rhs) const;
236 bool operator<=(const Time &rhs) const;
237 bool operator>=(const Time &rhs) const;
238
239 #ifndef SWIG
240 // For gtest etc.
241 friend std::ostream &operator<<(std::ostream &os, const Time &time);
242 #endif // SWIG
243
Brian Silverman52aeeac2013-08-28 16:20:53 -0700244 int32_t constexpr sec() const { return sec_; }
brians343bc112013-02-10 01:53:46 +0000245 void set_sec(int32_t sec) { sec_ = sec; }
Brian Silverman52aeeac2013-08-28 16:20:53 -0700246 int32_t constexpr nsec() const { return nsec_; }
brians343bc112013-02-10 01:53:46 +0000247 void set_nsec(int32_t nsec) {
248 nsec_ = nsec;
249 Check();
250 }
251
Brian Silverman3204dd82013-03-12 18:42:01 -0700252 // Absolute value.
253 Time abs() const {
254 if (*this > Time(0, 0)) return *this;
Brian Silvermanf3cbebd2013-03-19 16:53:18 -0700255 if (nsec_ == 0) return Time(-sec_, 0);
Brian Silverman3204dd82013-03-12 18:42:01 -0700256 return Time(-sec_ - 1, kNSecInSec - nsec_);
257 }
258
brians343bc112013-02-10 01:53:46 +0000259 private:
260 int32_t sec_, nsec_;
Brian Silverman52aeeac2013-08-28 16:20:53 -0700261
262 // LOG(FATAL)s if nsec is >= kNSecInSec or negative.
263 static void CheckImpl(int32_t nsec);
264 void Check() { CheckImpl(nsec_); }
265 // A constexpr version of CheckImpl that returns the given value when it
Brian Silverman6659bc32013-10-16 10:31:32 -0700266 // succeeds or evaluates to non-constexpr and returns 0 when it fails.
267 // This will result in the usual LOG(FATAL) if this is used where it isn't
268 // required to be constexpr or a compile error if it is.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700269 static constexpr int32_t CheckConstexpr(int32_t nsec) {
270 return (nsec >= kNSecInSec || nsec < 0) ? CheckImpl(nsec), 0 : nsec;
271 }
272
273#ifdef SWIG
274#undef constexpr
275#endif // SWIG
brians343bc112013-02-10 01:53:46 +0000276};
277
278// Sleeps for the amount of time represented by time counted by clock.
279void SleepFor(const Time &time, clockid_t clock = Time::kDefaultClock);
280// Sleeps until clock is at the time represented by time.
281void SleepUntil(const Time &time, clockid_t clock = Time::kDefaultClock);
282
Brian Silvermand0575692015-02-21 16:24:02 -0500283// Sets the global offset for all times so ::aos::time::Time::Now() will return
284// now.
285// There is no synchronization here, so this is only safe when only a single
286// task is running.
287// This is only allowed when the shared memory core infrastructure has been
288// initialized in this process.
289void OffsetToNow(const Time &now);
290
Brian Silvermanb407c672014-04-09 11:58:37 -0700291// RAII class that freezes Time::Now() (to avoid making large numbers of
292// syscalls to find the real time).
293class TimeFreezer {
294 public:
Austin Schuh6a6f90c2016-11-25 21:36:42 -0800295 TimeFreezer() { EnableMockTime(monotonic_clock::now()); }
296 ~TimeFreezer() { DisableMockTime(); }
Brian Silvermanb407c672014-04-09 11:58:37 -0700297
298 private:
299 DISALLOW_COPY_AND_ASSIGN(TimeFreezer);
300};
301
brians343bc112013-02-10 01:53:46 +0000302} // namespace time
303} // namespace aos
304
Austin Schuh793d6b92016-05-01 13:28:14 -0700305namespace std {
306namespace this_thread {
307// Template specialization for monotonic_clock, since we can use clock_nanosleep
308// with TIMER_ABSTIME and get very precise absolute time sleeps.
309template <>
310void sleep_until(const ::aos::monotonic_clock::time_point &end_time);
311
312} // namespace this_thread
313} // namespace std
314
315
brians343bc112013-02-10 01:53:46 +0000316#endif // AOS_COMMON_TIME_H_