12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- #include "core/Clock.hpp"
- #include <chrono>
- #include <thread>
- #include "ErrorSimulator.hpp"
- using Core::Clock;
- Clock::Clock() : index(0), last(0), sum(0), time({}) {
- }
- i64 Clock::update() {
- i64 current = getNanos();
- if(current < 0) {
- return current;
- }
- if(last == 0) {
- last = current;
- return 0;
- }
- index = (index + 1) & (time.getLength() - 1);
- sum -= time[index];
- time[index] = current - last;
- sum += time[index];
- last = current;
- return time[index];
- }
- float Core::Clock::getUpdatesPerSecond() const {
- return (time.getLength() * 1000000000.0f) / static_cast<float>(sum);
- }
- bool Clock::sleepNanos(i64 nanos) {
- try {
- FAIL_STEP_THROW();
- std::this_thread::sleep_for(std::chrono::nanoseconds(nanos));
- } catch(...) {
- return true;
- }
- return false;
- }
- bool Clock::sleepMillis(i64 millis) {
- return sleepNanos(millis * 1'000'000l);
- }
- i64 Clock::getNanos(void) {
- try {
- FAIL_STEP_THROW();
- using namespace std::chrono;
- return duration_cast<nanoseconds>(
- high_resolution_clock::now().time_since_epoch())
- .count();
- } catch(std::exception& e) {
- return -1;
- }
- }
|