1. ## QueryPerformanceCounter usage

I have come across the following example code when I tried to find example usage of this function supplied by WinAPI:

Code:
```__int64 freq, start, end, diff;

// start
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
QueryPerformanceCounter((LARGE_INTEGER*)&start);

// code to measure
Sleep(1234);

// end
QueryPerformanceCounter((LARGE_INTEGER*)&end);
diff = ((end - start) * 1000) / freq;

unsigned int milliseconds = (unsigned int)(diff & 0xffffffff);
printf("It took %u ms\n", milliseconds);```
For the line highlighted in red, as I stepped through the debugger, it appears diff is in the order of milliseconds, but I have trouble finding documentation saying that it is so. Can someone confirm that this is indeed the case?

Thanks.

2. diff is calculated by subtracting start from end. This gives us a time in ticks of the freq HZ counter. Knowing that it took 1131827192 clocks of a 1.9312MHz clock (I made those numbers up) is pretty pointless, because it means nothing to most human beings.

To make that time into seconds, we divide by freq (1.9312MHz in this example). To make it milliseconds, we multiply by 1000. Since it is integer math, multiply first, then divide to make it more precise.

(The numbers above are completely ficticious - although I think one of the PC timers actually run at about 1.9something MHz, I just made the rest of the number up)

--
Mats

3. Thanks for the explanation. Previously, I was using clock() function to time function calls, which has proven to be not precise enough to get anything other than 0 most of the time. When I was using clock() function, doing something similar (although without dividing the frequency) got me the time in seconds, not milliseconds. That was the major source of my confusion.

4. Originally Posted by stanlvw
Thanks for the explanation. Previously, I was using clock() function to time function calls, which has proven to be not precise enough to get anything other than 0 most of the time. When I was using clock() function, doing something similar (although without dividing the frequency) got me the time in seconds, not milliseconds. That was the major source of my confusion.
Of course, you can use the same trick for clock():
Code:
```clock_t t = clock();
... do something that takes a bit of time ...
t = clock() - t;
// t is now the number of clock-ticks.
t = 1000 * t / CLOCKS_PER_TICK
// t is now milliseconds.```
I often tend to use seconds in a floating point value, instead of milliseconds, but both will work.

--
Mats