Search code examples
c++timer64-bitperformancecounter

QueryPerformanceCounter throwing incorrect numbers


I am using QueryPerformanceCounter to measure the time of some functions/operations. It used to give me correct numbers, for instance, I could test Sleep(1000) and it would return a time very close to 1 second. Now, it returns a time very different. I am not sure what the issue is as the code hasn't changed at all. Here is the code:

Expected Output:

duration : 1.000 seconds

Actual Output:

duration : 187.988 seconds

Code:

#include <windows.h>
#pragma comment (lib, "winmm.lib")


struct Clock{

Clock(){}
virtual ~Clock(){}
void start();
void stop();
long double duration();

LARGE_INTEGER _start, _end, _freq;

};

void Clock::start(){
_start.QuadPart = 0;
QueryPerformanceCounter(&_freq);
QueryPerformanceCounter(&_start);
}

void Clock::stop(){
QueryPerformanceCounter(&_end);
}

long double Clock::duration(){
//microseconds
LARGE_INTEGER delta;
delta.QuadPart = (_end.QuadPart - _start.QuadPart) * 1000000;
long double the_duration = ((long double)delta.QuadPart) / _freq.QuadPart;
std::cout << "duration : " << the_duration << " seconds" << std::endl;
return the_duration;
}





void main(){

Clock clock;

clock.start();
Sleep(1000);
clock.stop();
clock.duration();

std::cin.get();
}

Solution

  • You are assuming that the frequency from the performance counter is exactly 1000000 Hz.

    You need to call QueryPerformanceFrequency instead, as the frequency can vary (some kernels use the motherboard's 1.024 MHz timer, others use the CPUs time-stamp-counter, which runs at approximately the CPU's clock frequency).