Clock.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "utils/Clock.h"
  2. #include <threads.h>
  3. #include <time.h>
  4. Core::Clock::Clock() : index(0), last(0), sum(0), time(0) {
  5. }
  6. bool Core::Clock::update(Clock::Nanos& n) {
  7. Nanos current = 0;
  8. if(getNanos(current)) {
  9. return true;
  10. } else if(last == 0) {
  11. last = current;
  12. n = 0;
  13. return false;
  14. }
  15. index = (index + 1) & (LENGTH - 1);
  16. sum -= time[index];
  17. time[index] = current - last;
  18. sum += time[index];
  19. last = current;
  20. n = time[index];
  21. return false;
  22. }
  23. float Core::Clock::getUpdatesPerSecond() const {
  24. return (LENGTH * 1000000000.0f) / static_cast<float>(sum);
  25. }
  26. bool Core::Clock::getNanos(Clock::Nanos& n) {
  27. struct timespec ts;
  28. if(timespec_get(&ts, TIME_UTC) == 0) {
  29. return CORE_ERROR(Error::TIME_NOT_AVAILABLE);
  30. }
  31. n = static_cast<Clock::Nanos>(ts.tv_sec) * 1'000'000'000L +
  32. static_cast<Clock::Nanos>(ts.tv_nsec);
  33. return false;
  34. }
  35. bool Core::Clock::wait(Nanos nanos) const {
  36. struct timespec t;
  37. t.tv_nsec = nanos % 1'000'000'000;
  38. t.tv_sec = nanos / 1'000'000'000;
  39. return CORE_ERROR(Error::SLEEP_INTERRUPTED, thrd_sleep(&t, nullptr) != 0);
  40. }