#include <chrono>
#include <thread>

#include "server/Clock.h"

Clock::Clock() : last(getNanos()), index(0), sum(0), time(0) {
}

u64 Clock::update() {
    index = (index + 1) & (length - 1);
    u64 current = getNanos();
    sum -= time[index];
    time[index] = current - last;
    sum += time[index];
    last = current;
    return time[index];
}

u64 Clock::getLength() const {
    return length;
}

float Clock::getUpdatesPerSecond() const {
    return length * (1000000000.0f / sum);
}

u64 Clock::getNanos() const {
    return std::chrono::steady_clock::now().time_since_epoch().count();
}

void Clock::wait(u64 nanos) const {
    std::this_thread::sleep_for(std::chrono::nanoseconds(nanos));
}