C/C++ GetTickCount 函数实现,支持 Linux、Windows

Windows 平台可以替换为  GetTickCount64 函数,而不必使用PDH库使用性能计数器的方法。

    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
    }

你可能感兴趣的:(C/C++,c语言,c++,单片机)