Brian | 3afd6fc | 2014-04-02 20:41:49 -0700 | [diff] [blame] | 1 | #ifndef AOS_COMMON_UTIL_PHASED_LOOP_H_ |
| 2 | #define AOS_COMMON_UTIL_PHASED_LOOP_H_ |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 3 | |
Brian Silverman | dcaa3f7 | 2015-11-29 05:32:08 +0000 | [diff] [blame^] | 4 | #include "aos/common/time.h" |
| 5 | |
| 6 | #include "aos/common/logging/logging.h" |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 7 | |
| 8 | namespace aos { |
| 9 | namespace time { |
| 10 | |
| 11 | // Will not be accurate if ms isn't a factor of 1000. |
| 12 | // offset is in us. |
Brian Silverman | dcaa3f7 | 2015-11-29 05:32:08 +0000 | [diff] [blame^] | 13 | // DEPRECATED(Brian): Use PhasedLoop instead. |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 14 | void PhasedLoopXMS(int ms, int offset); |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 15 | |
Brian Silverman | dcaa3f7 | 2015-11-29 05:32:08 +0000 | [diff] [blame^] | 16 | // Handles sleeping until a fixed offset from some time interval. |
| 17 | class PhasedLoop { |
| 18 | public: |
| 19 | // For example, with interval = 1s and offset = 0.1s this will fire at: |
| 20 | // 0.1s |
| 21 | // 1.1s |
| 22 | // ... |
| 23 | // 10000.1s |
| 24 | // offset must be >= Time::kZero and < interval. |
| 25 | PhasedLoop(const Time &interval, const Time &offset = Time::kZero) |
| 26 | : interval_(interval), offset_(offset), last_time_(offset) { |
| 27 | CHECK_GE(offset, Time::kZero); |
| 28 | CHECK_GT(interval, Time::kZero); |
| 29 | CHECK_LT(offset, interval); |
| 30 | Reset(); |
| 31 | } |
| 32 | |
| 33 | // Resets the count of skipped iterations. |
| 34 | // Iterate(now) will return 1 and set sleep_time() to something within |
| 35 | // interval of now. |
| 36 | void Reset(const Time &now = Time::Now()) { Iterate(now - interval_); } |
| 37 | |
| 38 | // Calculates the next time to run after now. |
| 39 | // The result can be retrieved with sleep_time(). |
| 40 | // Returns the number of iterations which have passed (1 if this is called |
| 41 | // often enough). This can be < 1 iff now goes backwards between calls. |
| 42 | int Iterate(const Time &now = Time::Now()); |
| 43 | |
| 44 | // Sleeps until the next time and returns the number of iterations which have |
| 45 | // passed. |
| 46 | int SleepUntilNext() { |
| 47 | const int r = Iterate(Time::Now()); |
| 48 | SleepUntil(sleep_time()); |
| 49 | return r; |
| 50 | } |
| 51 | |
| 52 | const Time &sleep_time() const { return last_time_; } |
| 53 | |
| 54 | private: |
| 55 | const Time interval_, offset_; |
| 56 | |
| 57 | // The time we most recently slept until. |
| 58 | Time last_time_ = Time::kZero; |
| 59 | }; |
| 60 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 61 | } // namespace time |
| 62 | } // namespace aos |
| 63 | |
Brian | 3afd6fc | 2014-04-02 20:41:49 -0700 | [diff] [blame] | 64 | #endif // AOS_COMMON_UTIL_PHASED_LOOP_H_ |