QueryPerformanceCounter和奇怪的结果

时间:2015-07-09 19:04:24

标签: c++ performancecounter

我想使用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());

        // ...
    }
}

这是我带有负数的奇怪结果:

enter image description here

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

您将double打印为浮动,使用%f

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