Clock.cpp 757 B

12345678910111213141516171819202122232425262728293031
  1. #include <chrono>
  2. #include <thread>
  3. #include "utils/Clock.h"
  4. Clock::Clock() : index(0), last(getNanos()), sum(0), time(0) {
  5. }
  6. Clock::Nanos Clock::update() {
  7. index = (index + 1) & (LENGTH - 1);
  8. Nanos current = getNanos();
  9. sum -= time[index];
  10. time[index] = current - last;
  11. sum += time[index];
  12. last = current;
  13. return time[index];
  14. }
  15. float Clock::getUpdatesPerSecond() const {
  16. return (LENGTH * 1000000000.0f) / sum;
  17. }
  18. Clock::Nanos Clock::getNanos() const {
  19. return std::chrono::duration_cast<std::chrono::nanoseconds>(
  20. std::chrono::high_resolution_clock::now().time_since_epoch())
  21. .count();
  22. }
  23. void Clock::wait(Nanos nanos) const {
  24. std::this_thread::sleep_for(std::chrono::nanoseconds(nanos));
  25. }