Home > Backend Development > C++ > How Can QueryPerformanceCounter Achieve Accurate Time Measurement in C ?

How Can QueryPerformanceCounter Achieve Accurate Time Measurement in C ?

Linda Hamilton
Release: 2024-12-26 00:24:08
Original
159 people have browsed it

How Can QueryPerformanceCounter Achieve Accurate Time Measurement in C  ?

Implementing QueryPerformanceCounter for Accurate Time Measurement

QueryPerformanceCounter is a highly precise function provided by Microsoft Windows for measuring time intervals in microseconds. To implement it effectively in C , let's dissect its usage step by step.

Initially, you need to include the necessary header file:

#include <windows.h>
Copy after login

Next, declare two global variables to store the performance counter frequency and starting point:

double PCFreq = 0.0;
__int64 CounterStart = 0;
Copy after login

The StartCounter() function initializes the performance counter:

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&amp;li))
        cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&amp;li);
    CounterStart = li.QuadPart;
}
Copy after login

QueryPerformanceFrequency retrieves the counter's frequency, and QueryPerformanceCounter records the current value.

To measure time elapsed since StartCounter was called, use the GetCounter() function:

double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&amp;li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}
Copy after login

The function calculates the elapsed time by comparing the current counter value to the starting value, adjusting for the counter's frequency.

Example Usage:

StartCounter();
Sleep(1000);
cout << GetCounter() <<"\n";
Copy after login

This program should output a number close to 1000, demonstrating the accuracy of the counter for measuring time durations in microseconds.

You can customize the precision of the counter by modifying the PCFreq calculation:

  • Seconds: PCFreq = double(li.QuadPart);
  • Microseconds: PCFreq = double(li.QuadPart)/1000000.0;

The choice depends on your desired level of granularity.

The above is the detailed content of How Can QueryPerformanceCounter Achieve Accurate Time Measurement in C ?. 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