cleaned/added features to some timing stuff
diff --git a/aos/common/control_loop/Timing.cpp b/aos/common/control_loop/Timing.cpp
index 6db179c..3a58036 100644
--- a/aos/common/control_loop/Timing.cpp
+++ b/aos/common/control_loop/Timing.cpp
@@ -9,12 +9,11 @@
namespace time {
void PhasedLoopXMS(int ms, int offset) {
- // TODO(brians): Rewrite this cleaner.
// TODO(brians): Tests!
- int64_t period_nsec = Time::InMS(ms).nsec();
- SleepUntil(Time::InNS((Time::Now().ToNSec() / period_nsec +
- static_cast<int64_t>(1)) * period_nsec +
- Time::InUS(offset).ToNSec()));
+ const Time frequency = Time::InMS(ms);
+ SleepUntil((Time::Now() / frequency.ToNSec()) *
+ frequency.ToNSec() +
+ frequency + Time::InUS(offset));
}
} // namespace timing
diff --git a/aos/common/time.h b/aos/common/time.h
index 14cc19e..ea703f7 100644
--- a/aos/common/time.h
+++ b/aos/common/time.h
@@ -79,9 +79,15 @@
static Time Now(clockid_t clock = kDefaultClock);
// Constructs a Time representing seconds.
+ // TODO(brians): fix and test the negative cases for all of these
static Time InSeconds(double seconds) {
- return Time(static_cast<int32_t>(seconds),
- (seconds - static_cast<int32_t>(seconds)) * kNSecInSec);
+ if (seconds < 0.0) {
+ return Time(static_cast<int32_t>(seconds) - 1,
+ (seconds - static_cast<int32_t>(seconds) + 1.0) * kNSecInSec);
+ } else {
+ return Time(static_cast<int32_t>(seconds),
+ (seconds - static_cast<int32_t>(seconds)) * kNSecInSec);
+ }
}
// Constructs a time representing microseconds.
@@ -92,7 +98,12 @@
// Constructs a time representing microseconds.
static Time InUS(int useconds) {
- return Time(useconds / kUSecInSec, (useconds % kUSecInSec) * kNSecInUSec);
+ if (useconds < 0) {
+ return Time(useconds / kUSecInSec - 1,
+ (useconds % kUSecInSec) * kNSecInUSec + kNSecInSec);
+ } else {
+ return Time(useconds / kUSecInSec, (useconds % kUSecInSec) * kNSecInUSec);
+ }
}
// Constructs a time representing mseconds.
@@ -126,6 +137,13 @@
(static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInMSec));
}
+ // Returns the time represent in microseconds.
+ // TODO(brians): test this
+ int64_t ToUSec() const {
+ return static_cast<int64_t>(sec_) * static_cast<int64_t>(kUSecInSec) +
+ (static_cast<int64_t>(nsec_) / static_cast<int64_t>(kNSecInUSec));
+ }
+
// Returns the time represented in fractional seconds.
double ToSeconds() const {
return static_cast<double>(sec_) + static_cast<double>(nsec_) / kNSecInSec;