ratekeeper.cc 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include "common/ratekeeper.h"
  2. #include <algorithm>
  3. #include "common/swaglog.h"
  4. #include "common/timing.h"
  5. #include "common/util.h"
  6. RateKeeper::RateKeeper(const std::string &name, float rate, float print_delay_threshold)
  7. : name(name),
  8. print_delay_threshold(std::max(0.f, print_delay_threshold)) {
  9. interval = 1 / rate;
  10. last_monitor_time = seconds_since_boot();
  11. next_frame_time = last_monitor_time + interval;
  12. }
  13. bool RateKeeper::keepTime() {
  14. bool lagged = monitorTime();
  15. if (remaining_ > 0) {
  16. util::sleep_for(remaining_ * 1000);
  17. }
  18. return lagged;
  19. }
  20. bool RateKeeper::monitorTime() {
  21. ++frame_;
  22. last_monitor_time = seconds_since_boot();
  23. remaining_ = next_frame_time - last_monitor_time;
  24. bool lagged = remaining_ < 0;
  25. if (lagged) {
  26. if (print_delay_threshold > 0 && remaining_ < -print_delay_threshold) {
  27. LOGW("%s lagging by %.2f ms", name.c_str(), -remaining_ * 1000);
  28. }
  29. next_frame_time = last_monitor_time + interval;
  30. } else {
  31. next_frame_time += interval;
  32. }
  33. return lagged;
  34. }