blob: ba795a93d0e272b645a82407c879abd09497fbd7 [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 Schuh793d6b92016-05-01 13:28:14 -070035};
36
brians343bc112013-02-10 01:53:46 +000037namespace time {
38
39// A nice structure for representing times.
40// 0 <= nsec_ < kNSecInSec should always be true. All functions here will make
41// sure that that is true if it was on all inputs (including *this).
42//
Brian Silverman6659bc32013-10-16 10:31:32 -070043// Negative times are supported so that all of the normal arithmetic identities
44// work. nsec_ is still always positive.
45//
brians343bc112013-02-10 01:53:46 +000046// The arithmetic and comparison operators are overloaded because they make
47// complete sense and are very useful. The default copy and assignment stuff is
Brian Silverman6659bc32013-10-16 10:31:32 -070048// left because it works fine. Multiplication of Times by Times is
brians343bc112013-02-10 01:53:46 +000049// not implemented because I can't think of any uses for them and there are
Brian Silverman6659bc32013-10-16 10:31:32 -070050// multiple ways to do it. Division of Times by Times is implemented as the
51// ratio of them. Multiplication, division, and modulus of Times by integers are
Brian Silverman0534df62014-05-26 21:19:15 -070052// implemented as interpreting the argument as nanoseconds. Modulus takes the
53// sign from the first operand.
brians343bc112013-02-10 01:53:46 +000054struct Time {
Brian Silverman52aeeac2013-08-28 16:20:53 -070055#ifdef SWIG
56// All of the uses of constexpr here can safely be simply removed.
57// NOTE: This means that relying on the fact that constexpr implicitly makes
Brian Silverman6659bc32013-10-16 10:31:32 -070058// member functions const is not valid, so they all have to be explicitly marked
59// const.
Brian Silverman52aeeac2013-08-28 16:20:53 -070060#define constexpr
61#endif // SWIG
brians343bc112013-02-10 01:53:46 +000062 public:
63 static const int32_t kNSecInSec = 1000000000;
64 static const int32_t kNSecInMSec = 1000000;
65 static const int32_t kNSecInUSec = 1000;
66 static const int32_t kMSecInSec = 1000;
67 static const int32_t kUSecInSec = 1000000;
Brian Silvermandcaa3f72015-11-29 05:32:08 +000068
69 static const Time kZero;
70
Brian Silverman92c3f1e2015-12-08 20:21:31 -050071 explicit constexpr Time(int32_t sec = 0, int32_t nsec = 0)
Brian Silverman52aeeac2013-08-28 16:20:53 -070072 : sec_(sec), nsec_(CheckConstexpr(nsec)) {
brians343bc112013-02-10 01:53:46 +000073 }
74 #ifndef SWIG
Brian Silverman52aeeac2013-08-28 16:20:53 -070075 explicit constexpr Time(const struct timespec &value)
76 : sec_(value.tv_sec), nsec_(CheckConstexpr(value.tv_nsec)) {
brians343bc112013-02-10 01:53:46 +000077 }
78 struct timespec ToTimespec() const {
79 struct timespec ans;
80 ans.tv_sec = sec_;
81 ans.tv_nsec = nsec_;
82 return ans;
83 }
Brian Silverman52aeeac2013-08-28 16:20:53 -070084 explicit constexpr Time(const struct timeval &value)
85 : sec_(value.tv_sec), nsec_(CheckConstexpr(value.tv_usec * kNSecInUSec)) {
brians57dd5822013-02-27 21:44:15 +000086 }
87 struct timeval ToTimeval() const {
88 struct timeval ans;
89 ans.tv_sec = sec_;
90 ans.tv_usec = nsec_ / kNSecInUSec;
91 return ans;
92 }
brians343bc112013-02-10 01:53:46 +000093 #endif // SWIG
Brian Silverman3204dd82013-03-12 18:42:01 -070094
Brian Silverman14fd0fb2014-01-14 21:42:01 -080095 // CLOCK_MONOTONIC on linux and CLOCK_REALTIME on the cRIO because the
brians343bc112013-02-10 01:53:46 +000096 // cRIO doesn't have any others.
97 // CLOCK_REALTIME is the default realtime clock and CLOCK_MONOTONIC doesn't
98 // change when somebody changes the wall clock (like the ntp deamon or
99 // whatever). See clock_gettime(2) for details.
100 //
101 // This is the clock that code that just wants to sleep for a certain amount
102 // of time or measure how long something takes should use.
103 #ifndef __VXWORKS__
104 static const clockid_t kDefaultClock = CLOCK_MONOTONIC;
105 #else
106 static const clockid_t kDefaultClock = CLOCK_REALTIME;
107 #endif
108 // Creates a Time representing the current value of the specified clock or
109 // dies.
110 static Time Now(clockid_t clock = kDefaultClock);
111
112 // Constructs a Time representing seconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700113 static constexpr Time InSeconds(double seconds) {
114 return (seconds < 0.0) ?
115 Time(static_cast<int32_t>(seconds) - 1,
116 (seconds - static_cast<int32_t>(seconds) + 1.0) * kNSecInSec) :
117 Time(static_cast<int32_t>(seconds),
118 (seconds - static_cast<int32_t>(seconds)) * kNSecInSec);
brians343bc112013-02-10 01:53:46 +0000119 }
120
121 // Constructs a time representing microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700122 static constexpr Time InNS(int64_t nseconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000123 return (nseconds < 0)
124 ? Time((nseconds - 1) / static_cast<int64_t>(kNSecInSec) - 1,
125 (((nseconds - 1) % kNSecInSec) + 1) + kNSecInSec)
126 : Time(nseconds / static_cast<int64_t>(kNSecInSec),
127 nseconds % kNSecInSec);
brians343bc112013-02-10 01:53:46 +0000128 }
129
130 // Constructs a time representing microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700131 static constexpr Time InUS(int useconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000132 return (useconds < 0)
133 ? Time((useconds + 1) / kUSecInSec - 1,
134 (((useconds + 1) % kUSecInSec) - 1) * kNSecInUSec +
135 kNSecInSec)
136 : Time(useconds / kUSecInSec,
137 (useconds % kUSecInSec) * kNSecInUSec);
brians343bc112013-02-10 01:53:46 +0000138 }
139
140 // Constructs a time representing mseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700141 static constexpr Time InMS(int mseconds) {
Brian Silvermandcaa3f72015-11-29 05:32:08 +0000142 return (mseconds < 0)
143 ? Time((mseconds + 1) / kMSecInSec - 1,
144 (((mseconds + 1) % kMSecInSec) - 1) * kNSecInMSec +
145 kNSecInSec)
146 : Time(mseconds / kMSecInSec,
147 (mseconds % kMSecInSec) * kNSecInMSec);
148 }
149
150 // Construct a time representing the period of hertz.
Austin Schuh8aec1ed2016-05-01 13:29:20 -0700151 static constexpr ::std::chrono::nanoseconds FromRate(int hertz) {
152 return ::std::chrono::duration_cast<::std::chrono::nanoseconds>(
153 ::std::chrono::seconds(1)) /
154 hertz;
brians343bc112013-02-10 01:53:46 +0000155 }
156
157 // Checks whether or not this time is within amount nanoseconds of other.
158 bool IsWithin(const Time &other, int64_t amount) const;
159
160 // Returns the time represented all in nanoseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700161 int64_t constexpr ToNSec() const {
brians343bc112013-02-10 01:53:46 +0000162 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kNSecInSec) +
163 static_cast<int64_t>(nsec_);
164 }
165#ifdef __VXWORKS__
166 // Returns the time represented all in system clock ticks. The system clock
167 // rate is retrieved using sysClkRateGet().
168 int ToTicks() const {
169 return ToNSec() / static_cast<int64_t>(kNSecInSec / sysClkRateGet());
170 }
Brian Silverman3204dd82013-03-12 18:42:01 -0700171 // Constructs a Time representing ticks.
172 static Time InTicks(int ticks) {
Brian Silvermanffe3d712013-03-15 21:35:59 -0700173 return Time::InSeconds(static_cast<double>(ticks) / sysClkRateGet());
Brian Silverman3204dd82013-03-12 18:42:01 -0700174 }
brians343bc112013-02-10 01:53:46 +0000175#endif
176
177 // Returns the time represented in milliseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700178 int64_t constexpr ToMSec() const {
brians343bc112013-02-10 01:53:46 +0000179 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kMSecInSec) +
180 (static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInMSec));
181 }
182
Brian Silverman7645d2f2013-03-30 18:53:56 -0700183 // Returns the time represent in microseconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700184 int64_t constexpr ToUSec() const {
Brian Silverman7645d2f2013-03-30 18:53:56 -0700185 return static_cast<int64_t>(sec_) * static_cast<int64_t>(kUSecInSec) +
186 (static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInUSec));
187 }
188
briansf0165ca2013-03-02 06:17:47 +0000189 // Returns the time represented in fractional seconds.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700190 double constexpr ToSeconds() const {
briansf0165ca2013-03-02 06:17:47 +0000191 return static_cast<double>(sec_) + static_cast<double>(nsec_) / kNSecInSec;
192 }
193
brians343bc112013-02-10 01:53:46 +0000194 #ifndef SWIG
195 Time &operator+=(const Time &rhs);
196 Time &operator-=(const Time &rhs);
197 Time &operator*=(int32_t rhs);
198 Time &operator/=(int32_t rhs);
199 Time &operator%=(int32_t rhs);
Brian Silverman0079a9d2013-10-24 15:57:35 -0700200 Time &operator%=(double rhs) = delete;
201 Time &operator*=(double rhs) = delete;
202 Time &operator/=(double rhs) = delete;
203 const Time operator*(double rhs) const = delete;
204 const Time operator/(double rhs) const = delete;
205 const Time operator%(double rhs) const = delete;
brians343bc112013-02-10 01:53:46 +0000206 #endif
207 const Time operator+(const Time &rhs) const;
208 const Time operator-(const Time &rhs) const;
209 const Time operator*(int32_t rhs) const;
210 const Time operator/(int32_t rhs) const;
Brian Silverman2e0dcfd2013-03-30 22:44:40 -0700211 double operator/(const Time &rhs) const;
brians343bc112013-02-10 01:53:46 +0000212 const Time operator%(int32_t rhs) const;
213
Brian Silverman0079a9d2013-10-24 15:57:35 -0700214 const Time operator-() const;
215
brians343bc112013-02-10 01:53:46 +0000216 bool operator==(const Time &rhs) const;
217 bool operator!=(const Time &rhs) const;
218 bool operator<(const Time &rhs) const;
219 bool operator>(const Time &rhs) const;
220 bool operator<=(const Time &rhs) const;
221 bool operator>=(const Time &rhs) const;
222
223 #ifndef SWIG
224 // For gtest etc.
225 friend std::ostream &operator<<(std::ostream &os, const Time &time);
226 #endif // SWIG
227
Brian Silverman52aeeac2013-08-28 16:20:53 -0700228 int32_t constexpr sec() const { return sec_; }
brians343bc112013-02-10 01:53:46 +0000229 void set_sec(int32_t sec) { sec_ = sec; }
Brian Silverman52aeeac2013-08-28 16:20:53 -0700230 int32_t constexpr nsec() const { return nsec_; }
brians343bc112013-02-10 01:53:46 +0000231 void set_nsec(int32_t nsec) {
232 nsec_ = nsec;
233 Check();
234 }
235
Brian Silverman3204dd82013-03-12 18:42:01 -0700236 // Absolute value.
237 Time abs() const {
238 if (*this > Time(0, 0)) return *this;
Brian Silvermanf3cbebd2013-03-19 16:53:18 -0700239 if (nsec_ == 0) return Time(-sec_, 0);
Brian Silverman3204dd82013-03-12 18:42:01 -0700240 return Time(-sec_ - 1, kNSecInSec - nsec_);
241 }
242
243 // Enables returning the mock time value for Now instead of checking the
Brian Silverman6da04272014-05-18 18:47:48 -0700244 // system clock.
Brian Silvermanb407c672014-04-09 11:58:37 -0700245 static void EnableMockTime(const Time &now = Now());
246 // Calls SetMockTime with the current actual time.
247 static void UpdateMockTime();
Brian Silverman3204dd82013-03-12 18:42:01 -0700248 // Sets now when time is being mocked.
Brian Silverman6659bc32013-10-16 10:31:32 -0700249 static void SetMockTime(const Time &now);
250 // Convenience function to just increment the mock time by a certain amount in
251 // a thread safe way.
252 static void IncrementMockTime(const Time &amount);
Brian Silverman3204dd82013-03-12 18:42:01 -0700253 // Disables mocking time.
254 static void DisableMockTime();
255
brians343bc112013-02-10 01:53:46 +0000256 private:
257 int32_t sec_, nsec_;
Brian Silverman52aeeac2013-08-28 16:20:53 -0700258
259 // LOG(FATAL)s if nsec is >= kNSecInSec or negative.
260 static void CheckImpl(int32_t nsec);
261 void Check() { CheckImpl(nsec_); }
262 // A constexpr version of CheckImpl that returns the given value when it
Brian Silverman6659bc32013-10-16 10:31:32 -0700263 // succeeds or evaluates to non-constexpr and returns 0 when it fails.
264 // This will result in the usual LOG(FATAL) if this is used where it isn't
265 // required to be constexpr or a compile error if it is.
Brian Silverman52aeeac2013-08-28 16:20:53 -0700266 static constexpr int32_t CheckConstexpr(int32_t nsec) {
267 return (nsec >= kNSecInSec || nsec < 0) ? CheckImpl(nsec), 0 : nsec;
268 }
269
270#ifdef SWIG
271#undef constexpr
272#endif // SWIG
brians343bc112013-02-10 01:53:46 +0000273};
274
275// Sleeps for the amount of time represented by time counted by clock.
276void SleepFor(const Time &time, clockid_t clock = Time::kDefaultClock);
277// Sleeps until clock is at the time represented by time.
278void SleepUntil(const Time &time, clockid_t clock = Time::kDefaultClock);
279
Brian Silvermand0575692015-02-21 16:24:02 -0500280// Sets the global offset for all times so ::aos::time::Time::Now() will return
281// now.
282// There is no synchronization here, so this is only safe when only a single
283// task is running.
284// This is only allowed when the shared memory core infrastructure has been
285// initialized in this process.
286void OffsetToNow(const Time &now);
287
Brian Silvermanb407c672014-04-09 11:58:37 -0700288// RAII class that freezes Time::Now() (to avoid making large numbers of
289// syscalls to find the real time).
290class TimeFreezer {
291 public:
292 TimeFreezer() {
293 Time::EnableMockTime();
294 }
295 ~TimeFreezer() {
296 Time::DisableMockTime();
297 }
298
299 private:
300 DISALLOW_COPY_AND_ASSIGN(TimeFreezer);
301};
302
brians343bc112013-02-10 01:53:46 +0000303} // namespace time
304} // namespace aos
305
Austin Schuh793d6b92016-05-01 13:28:14 -0700306namespace std {
307namespace this_thread {
308// Template specialization for monotonic_clock, since we can use clock_nanosleep
309// with TIMER_ABSTIME and get very precise absolute time sleeps.
310template <>
311void sleep_until(const ::aos::monotonic_clock::time_point &end_time);
312
313} // namespace this_thread
314} // namespace std
315
316
brians343bc112013-02-10 01:53:46 +0000317#endif // AOS_COMMON_TIME_H_