Home >Backend Development >C++ >How Can QueryPerformanceCounter Improve Timer Accuracy and How Is It Used?
What is QueryPerformanceCounter and How to Use It
To improve the timing accuracy of a Timer class, QueryPerformanceCounter can be a reliable option, particularly when seeking microsecond resolution.
Implementing QueryPerformanceCounter
To utilize QueryPerformanceCounter, follow these steps:
Initialize PCFreq:
LARGE_INTEGER li; if (!QueryPerformanceFrequency(&li)) cout << "QueryPerformanceFrequency failed!\n"; PCFreq = double(li.QuadPart) / 1000.0;
Start the Counter:
QueryPerformanceCounter(&li); CounterStart = li.QuadPart;
Get Time Elapsed:
double GetCounter() { QueryPerformanceCounter(&li); return double(li.QuadPart - CounterStart) / PCFreq; }
StartCounter(); Sleep(1000); cout << GetCounter() << "\n"; // Output: approximately 1000
By adjusting the division of PCFreq you can control the unit of time returned:
The above is the detailed content of How Can QueryPerformanceCounter Improve Timer Accuracy and How Is It Used?. For more information, please follow other related articles on the PHP Chinese website!