Created
February 5, 2022 18:00
-
-
Save tanoxyz/e15f2aa940803245b6362d76e81dc63b to your computer and use it in GitHub Desktop.
High precision (nanoseconds) time for windows and linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef UTIME_INCLUDED | |
#define UTIME_INCLUDED | |
#include <stdint.h> | |
void | |
UT_Init(void); | |
int64_t | |
UT_Time(void); | |
#if defined(__linux__) || defined(__unix__) | |
#include <time.h> | |
static struct timespec UT__initial_time = {0}; | |
void | |
UT_Init(void) { | |
clock_gettime(CLOCK_MONOTONIC_RAW, &UT__initial_time); | |
} | |
int64_t | |
UT_Time(void) { | |
const int64_t SECOND = 1000*1000*1000; | |
struct timespec current; | |
clock_gettime(CLOCK_MONOTONIC_RAW, ¤t); | |
int64_t result = (current.tv_sec - UT__initial_time.tv_sec) * (1 * SECOND); | |
result += current.tv_nsec - UT__initial_time.tv_nsec; | |
return result; | |
} | |
#elif defined(_WIN32) || defined(WIN32) | |
#include <windows.h> | |
static LARGE_INTEGER UT__initial_time = {0}; | |
static LARGE_INTEGER UT__time_freq = {0}; | |
void | |
UT_Init(void) { | |
QueryPerformanceFrequency(&UT__time_freq); | |
QueryPerformanceCounter(&UT__initial_time); | |
} | |
int64_t | |
UT_Time(void) { | |
const int64_t SECOND = 1000*1000*1000; | |
LARGE_INTEGER qpc_t; | |
QueryPerformanceCounter(&qpc_t); | |
int64_t counter_diff = qpc_t.QuadPart - UT__initial_time.QuadPart; | |
int64_t freq = UT__time_freq.QuadPart; | |
// This is to preserve the precission (from sokol time) | |
int64_t q = counter_diff / freq; | |
int64_t r = counter_diff % freq; | |
int64_t result = q * SECOND + (r * SECOND) / freq; | |
return result; | |
} | |
#elif defined (__wasm__) | |
#define UT__WA_JS(ret, name, args, ...) extern __attribute__((import_module("JS"), import_name(#name "|" #args "|" #__VA_ARGS__))) ret name args; | |
static int64_t UT__initial_time = 0; | |
UT__WA_JS(double, UT__JS_Get_time, (void), { | |
return Date.now(); | |
}); | |
void | |
UT_Init(void) { | |
UT__initial_time = (int64_t)UT__JS_Get_time(); | |
} | |
int64_t | |
UT_Time(void) { | |
int64_t MSECOND = 1000 * 1000; | |
int64_t result = MSECOND*((int64_t)UT__JS_Get_time() - UT__initial_time); | |
return result; | |
} | |
#endif | |
#endif // UTIME_INCLUDED | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment