How to use queryperformancecounter in c++?

To measure time and performance in C++, you need to follow these steps when using the QueryPerformanceCounter function:

  1. Include the Windows h header file, which contains the declaration of the QueryPerformanceCounter function.
#include <Windows.h>
  1. Declare a variable of type LARGE_INTEGER to store the value of the counter.
LARGE_INTEGER start, end, frequency;
  1. Call the QueryPerformanceFrequency function to retrieve the frequency of the counter, which indicates how many times the counter increases per second.
QueryPerformanceFrequency(&frequency);
  1. Call the QueryPerformanceCounter function to retrieve the current value of the counter.
QueryPerformanceCounter(&start);
  1. Execute code that needs to be timed.
  2. Call the QueryPerformanceCounter function to retrieve the current value of the counter.
QueryPerformanceCounter(&end);
  1. Calculate the time interval and convert it to seconds.
double elapsed = (end.QuadPart - start.QuadPart) / static_cast<double>(frequency.QuadPart);

The complete sample code is as follows:

#include <iostream>
#include <Windows.h>

int main() {
    LARGE_INTEGER start, end, frequency;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&start);

    // 执行需要计时的代码
    for (int i = 0; i < 1000000; ++i) {
        // Do something
    }

    QueryPerformanceCounter(&end);
    double elapsed = (end.QuadPart - start.QuadPart) / static_cast<double>(frequency.QuadPart);

    std::cout << "Elapsed time: " << elapsed << " seconds" << std::endl;

    return 0;
}

Please be advised:

  1. The counter value returned by the QueryPerformanceCounter function is a 64-bit integer and can be stored using the LARGE_INTEGER type.
  2. If the timing result is very small, it can be multiplied by an appropriate factor to convert to a more friendly unit, such as milliseconds or microseconds.
广告
Closing in 10 seconds
bannerAds