Clock.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "core/Clock.hpp"
  2. #include <chrono>
  3. #include <thread>
  4. #include "ErrorSimulator.hpp"
  5. using Core::Clock;
  6. Clock::Clock() : index(0), last(0), sum(0), time({}) {
  7. }
  8. i64 Clock::update() {
  9. i64 current = getNanos();
  10. if(current < 0) {
  11. return current;
  12. }
  13. if(last == 0) {
  14. last = current;
  15. return 0;
  16. }
  17. index = (index + 1) & (time.getLength() - 1);
  18. sum -= time[index];
  19. time[index] = current - last;
  20. sum += time[index];
  21. last = current;
  22. return time[index];
  23. }
  24. float Core::Clock::getUpdatesPerSecond() const {
  25. return (time.getLength() * 1000000000.0f) / static_cast<float>(sum);
  26. }
  27. bool Clock::sleepNanos(i64 nanos) {
  28. try {
  29. FAIL_STEP_THROW();
  30. std::this_thread::sleep_for(std::chrono::nanoseconds(nanos));
  31. } catch(...) {
  32. return true;
  33. }
  34. return false;
  35. }
  36. bool Clock::sleepMillis(i64 millis) {
  37. return sleepNanos(millis * 1'000'000l);
  38. }
  39. i64 Clock::getNanos(void) {
  40. try {
  41. FAIL_STEP_THROW();
  42. using namespace std::chrono;
  43. return duration_cast<nanoseconds>(
  44. high_resolution_clock::now().time_since_epoch())
  45. .count();
  46. } catch(std::exception& e) {
  47. return -1;
  48. }
  49. }