QueryPerformanceCounter 和奇怪的结果

QueryPerformanceCounter and weird results

我想使用 PerformanceCounter 来衡量我需要多少时间来完成某些操作。

我对 PerformanceCounter 和 C++ 了解不多。我在这里找到了一些代码:

How to use QueryPerformanceCounter?

我得到了奇怪的结果。这是我的尝试:

#include <Windows.h>

// ...

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if (!QueryPerformanceFrequency(&li))
        printf("QueryPerformanceFrequency failed!\n");

    PCFreq = double(li.QuadPart) / 1000.0;

    //printf("Performance counter resolution: %f", PCFreq);

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}

double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart - CounterStart) / PCFreq;
}

int main(int argc, const char** argv) {
    while (true) {
        StartCounter();
        Sleep(1000); // just a test
        printf("Query frame: %d\n", GetCounter());

        // ...
    }
}

这是我用负数得出的奇怪结果:

我的代码有什么问题?

您将双精度打印为浮点数,使用 %f:

printf("Query frame: %f\n", GetCounter());