Brian | 3afd6fc | 2014-04-02 20:41:49 -0700 | [diff] [blame] | 1 | #include "aos/common/util/phased_loop.h" |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 2 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 3 | namespace aos { |
| 4 | namespace time { |
| 5 | |
| 6 | void PhasedLoopXMS(int ms, int offset) { |
Brian Silverman | 7645d2f | 2013-03-30 18:53:56 -0700 | [diff] [blame] | 7 | const Time frequency = Time::InMS(ms); |
Brian Silverman | 0079a9d | 2013-10-24 15:57:35 -0700 | [diff] [blame] | 8 | SleepUntil((Time::Now() / static_cast<int32_t>(frequency.ToNSec())) * |
| 9 | static_cast<int32_t>(frequency.ToNSec()) + |
Brian Silverman | 7645d2f | 2013-03-30 18:53:56 -0700 | [diff] [blame] | 10 | frequency + Time::InUS(offset)); |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 11 | } |
| 12 | |
Brian Silverman | dcaa3f7 | 2015-11-29 05:32:08 +0000 | [diff] [blame] | 13 | int PhasedLoop::Iterate(const Time &now) { |
| 14 | const Time next_time = Time::InNS(((now - offset_).ToNSec() + 1) / |
| 15 | interval_.ToNSec() * interval_.ToNSec()) + |
| 16 | ((now < offset_) ? Time::kZero : interval_) + offset_; |
| 17 | |
| 18 | const Time difference = next_time - last_time_; |
| 19 | const int result = difference.ToNSec() / interval_.ToNSec(); |
| 20 | CHECK_EQ(difference, interval_ * result); |
| 21 | CHECK_EQ(0, (next_time - offset_).ToNSec() % interval_.ToNSec()); |
| 22 | CHECK_GE(next_time, now); |
| 23 | CHECK_LE(next_time - now, interval_); |
| 24 | last_time_ = next_time; |
| 25 | return result; |
| 26 | } |
| 27 | |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 28 | } // namespace timing |
| 29 | } // namespace aos |