Home > Backend Development > C++ > How Can QueryPerformanceCounter Improve Timer Accuracy and How Is It Used?

How Can QueryPerformanceCounter Improve Timer Accuracy and How Is It Used?

Barbara Streisand
Release: 2024-12-15 04:24:09
Original
982 people have browsed it

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:

  1. Initialize PCFreq:

    • Determine the performance counter frequency using QueryPerformanceFrequency(&li).
    • Convert the result to double and divide it by 1000 to obtain the frequency in microseconds.
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

PCFreq = double(li.QuadPart) / 1000.0;
Copy after login
  1. Start the Counter:

    • Record the initial count using QueryPerformanceCounter(&li).
    • Store this count in the CounterStart variable.
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
Copy after login
  1. Get Time Elapsed:

    • Call QueryPerformanceCounter(&li) to obtain the current count.
    • Calculate the time elapsed by subtracting the start count from the current count and dividing the result by PCFreq.
double GetCounter()
{
    QueryPerformanceCounter(&li);
    return double(li.QuadPart - CounterStart) / PCFreq;
}
Copy after login
  1. Example Usage:
StartCounter();
Sleep(1000);
cout << GetCounter() << "\n"; // Output: approximately 1000
Copy after login

By adjusting the division of PCFreq you can control the unit of time returned:

  • Milliseconds: /1000.0
  • Seconds: /1.0
  • Microseconds: /1000000.0

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template