Clock.cpp 1.2 KB

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