How to use queryperformancecounter in c++?
To measure time and performance in C++, you need to follow these steps when using the QueryPerformanceCounter function:
- Include the Windows h header file, which contains the declaration of the QueryPerformanceCounter function.
#include <Windows.h>
- Declare a variable of type LARGE_INTEGER to store the value of the counter.
LARGE_INTEGER start, end, frequency;
- Call the QueryPerformanceFrequency function to retrieve the frequency of the counter, which indicates how many times the counter increases per second.
QueryPerformanceFrequency(&frequency);
- Call the QueryPerformanceCounter function to retrieve the current value of the counter.
QueryPerformanceCounter(&start);
- Execute code that needs to be timed.
- Call the QueryPerformanceCounter function to retrieve the current value of the counter.
QueryPerformanceCounter(&end);
- 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:
- The counter value returned by the QueryPerformanceCounter function is a 64-bit integer and can be stored using the LARGE_INTEGER type.
- 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.