How to Determine Elapsed Time with QueryPerformanceCounter
QueryPerformanceCounter is a high-resolution performance counter API for Windows systems that allows for precise timing measurements. To implement it, follow these steps:
Include Necessary Headers:
#include <windows.h>
Define Performance Counter Variables:
Implement StartCounter Function:
Implement GetCounter Function:
Example Usage:
Code Snippet:
double PCFreq = 0.0; __int64 CounterStart = 0; void StartCounter() { LARGE_INTEGER li; if (!QueryPerformanceFrequency(&li)) cout << "QueryPerformanceFrequency failed!\n"; PCFreq = double(li.QuadPart) / 1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; } double GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; } int main() { StartCounter(); Sleep(1000); cout << GetCounter() << "\n"; return 0; }
This code snippet outputs a value close to 1000, demonstrating the use of QueryPerformanceCounter for precise timing measurements.
The above is the detailed content of How Can I Accurately Measure Elapsed Time Using QueryPerformanceCounter in Windows?. For more information, please follow other related articles on the PHP Chinese website!