0

I want to use PerformanceCounter to measure how much time I need for some operation.

I don't know much about PerformanceCounter and C++ in general. I found some code here:

How to use QueryPerformanceCounter?

I'm getting weird results with this. Here is my try:

#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());

        // ...
    }
}

And here is my weird result with negative numbers:

enter image description here

What is wrong with my code?

Community
  • 1
  • 1
Kamil
  • 13,363
  • 24
  • 88
  • 183

1 Answers1

1

You print a double as a float, use %f:

printf("Query frame: %f\n", GetCounter());
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • Oh dear, I just found it... It works perfect after I fixed that. – Kamil Jul 09 '15 at 19:08
  • For doubles, it may need to be %lf, not just %f. Also It's not clear why you divide frequency by 1000, unless you want the display to be in milliseconds instead of seconds. The syntax for type casting is wrong, for example you should use PCFreq = (double)li.QuadPart / 1000.; – rcgldr Jul 09 '15 at 22:13