在C++中使用QueryPerformanceCounter函数来测量时间和性能,需要进行以下步骤:
#include <Windows.h>
LARGE_INTEGER start, end, frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
执行需要计时的代码。
调用QueryPerformanceCounter函数来获取计数器的当前值。
QueryPerformanceCounter(&end);
double elapsed = (end.QuadPart - start.QuadPart) / static_cast<double>(frequency.QuadPart);
完整示例代码如下:
#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;
}
注意: