Home > Backend Development > C++ > How Can QueryPerformanceCounter Achieve Precise Time Measurement in Windows Applications?

How Can QueryPerformanceCounter Achieve Precise Time Measurement in Windows Applications?

Susan Sarandon
Release: 2024-12-17 15:59:11
Original
846 people have browsed it

How Can QueryPerformanceCounter Achieve Precise Time Measurement in Windows Applications?

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;
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

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