#include "timing.h"

#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

static uint64_t _QPC_freq = 0u;

rt_result InitTiming(void) {
    LARGE_INTEGER qpc_freq;
    if (!QueryPerformanceFrequency(&qpc_freq)) {
        return RT_UNKNOWN_ERROR;
    }
    _QPC_freq = (uint64_t)qpc_freq.QuadPart;
    double resolution = 1e6 * 1.0 / (double)_QPC_freq;
    rtLog("TIMING",
          "QPC Frequency: %llu ticks per second     Resolution: %.2lf us",
          _QPC_freq, resolution);

    return RT_SUCCESS;
}

RT_DLLEXPORT rt_timestamp rtTimeNow(void) {
    LARGE_INTEGER qpc;
    QueryPerformanceCounter(&qpc);
    return (rt_timestamp){.ticks = qpc.QuadPart, .ticks_per_second = _QPC_freq };
}

RT_DLLEXPORT rt_time_delta rtTimeBetween(rt_timestamp a, rt_timestamp b) {
    double a_secs, b_secs;
    a_secs = (double)a.ticks / (double)a.ticks_per_second;
    b_secs = (double)b.ticks / (double)b.ticks_per_second;
    return b_secs - a_secs;
}

#endif