Home > Backend Development > C++ > How Can I Accurately Measure Elapsed Time Using QueryPerformanceCounter in Windows?

How Can I Accurately Measure Elapsed Time Using QueryPerformanceCounter in Windows?

Linda Hamilton
Release: 2024-12-14 18:03:12
Original
545 people have browsed it

How Can I Accurately Measure Elapsed Time Using QueryPerformanceCounter in Windows?

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:

  1. Include Necessary Headers:

    #include <windows.h>
    Copy after login
  2. Define Performance Counter Variables:

    • PCFreq: Double variable to store the counter frequency in milliseconds.
    • CounterStart: Integer variable to store the starting counter value.
  3. Implement StartCounter Function:

    • Get the performance counter frequency in hertz using QueryPerformanceFrequency.
    • Convert the frequency to milliseconds.
    • Get the starting counter value using QueryPerformanceCounter.
  4. Implement GetCounter Function:

    • Get the current counter value using QueryPerformanceCounter.
    • Subtract the starting counter value to get the elapsed time in milliseconds.
    • Convert the elapsed time to the desired unit (e.g., seconds, microseconds).
  5. Example Usage:

    • Call StartCounter() to initialize the performance counter.
    • Use Sleep or a similar function to wait for a specific duration.
    • Call GetCounter() to retrieve the elapsed time.

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

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!

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