Implementing QueryPerformanceCounter for Accurate Time Measurement
QueryPerformanceCounter is a highly precise function provided by Microsoft Windows for measuring time intervals in microseconds. To implement it effectively in C , let's dissect its usage step by step.
Initially, you need to include the necessary header file:
#include <windows.h>
Next, declare two global variables to store the performance counter frequency and starting point:
double PCFreq = 0.0; __int64 CounterStart = 0;
The StartCounter() function initializes the performance counter:
void StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) cout << "QueryPerformanceFrequency failed!\n"; PCFreq = double(li.QuadPart)/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; }
QueryPerformanceFrequency retrieves the counter's frequency, and QueryPerformanceCounter records the current value.
To measure time elapsed since StartCounter was called, use the GetCounter() function:
double GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return double(li.QuadPart-CounterStart)/PCFreq; }
The function calculates the elapsed time by comparing the current counter value to the starting value, adjusting for the counter's frequency.
Example Usage:
StartCounter(); Sleep(1000); cout << GetCounter() <<"\n";
This program should output a number close to 1000, demonstrating the accuracy of the counter for measuring time durations in microseconds.
You can customize the precision of the counter by modifying the PCFreq calculation:
The choice depends on your desired level of granularity.
The above is the detailed content of How Can QueryPerformanceCounter Achieve Accurate Time Measurement in C ?. For more information, please follow other related articles on the PHP Chinese website!