How to Use QueryPerformanceCounter for Precise Time Measurement
QueryPerformanceCounter is a powerful Windows API function that provides high-precision timing capabilities. Understanding how to implement it is crucial for applications requiring precise time measurements, such as games and performance monitoring tools.
To use QueryPerformanceCounter, you need to declare a LARGE_INTEGER variable, which is a 64-bit integer used to store time values. The following code snippet shows how to initialize the variables:
LARGE_INTEGER li; double PCFreq;
The StartCounter() function initializes the performance counter by querying the current tick count and storing it in the CounterStart variable. It also calculates the performance counter frequency, which is used to convert ticks to seconds or milliseconds.
void StartCounter() { if (!QueryPerformanceFrequency(&li)) { cout << "QueryPerformanceFrequency failed!\n"; } PCFreq = double(li.QuadPart) / 1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; }
To retrieve the elapsed time since the counter was started, use the GetCounter() function. It queries the current tick count and subtracts the initial tick count from it, returning the elapsed time as a double.
double GetCounter() { QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; }
The provided code in the answer demonstrates how to use these functions to implement a simple timer that outputs the time elapsed after sleeping for one second.
By adjusting the PCFreq value, you can control the precision of the timer. Setting it to 1000.0 gives you millisecond precision, while 1000000.0 provides microsecond precision.
The above is the detailed content of How Can QueryPerformanceCounter Achieve Precise Time Measurement in Windows Applications?. For more information, please follow other related articles on the PHP Chinese website!