Windows 使用PDH(性能计数器)实现
Linux 使用 gettimeofday 函数实现
两者均支持微妙时间的获取,精度相对较高。
uint64_t GetTickCount(bool microseconds) noexcept {
#ifdef _WIN32
static LARGE_INTEGER ticksPerSecond; // (unsigned long long)GetTickCount64();
LARGE_INTEGER ticks;
if (!ticksPerSecond.QuadPart) {
QueryPerformanceFrequency(&ticksPerSecond);
}
QueryPerformanceCounter(&ticks);
if (microseconds) {
double cpufreq = (double)(ticksPerSecond.QuadPart / 1000000);
unsigned long long nowtick = (unsigned long long)(ticks.QuadPart / cpufreq);
return nowtick;
}
else {
unsigned long long seconds = ticks.QuadPart / ticksPerSecond.QuadPart;
unsigned long long milliseconds = 1000 * (ticks.QuadPart - (ticksPerSecond.QuadPart * seconds)) / ticksPerSecond.QuadPart;
unsigned long long nowtick = seconds * 1000 + milliseconds;
return (unsigned long long)nowtick;
}
#else
struct timeval tv;
gettimeofday(&tv, NULL);
if (microseconds) {
unsigned long long nowtick = (unsigned long long)tv.tv_sec * 1000000;
nowtick += tv.tv_usec;
return nowtick;
}
return ((unsigned long long)tv.tv_usec / 1000) + ((unsigned long long)tv.tv_sec * 1000);
#endif
}