C语言风格,Linux/Windows 平台获取当前 ticks(毫秒/微秒)

2023-12-20 02:19:26

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
    }

文章来源:https://blog.csdn.net/liulilittle/article/details/135062513
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。