Clock.cpp 1.3 KB

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