Clock.cpp 1.2 KB

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