在C++中使用QueryPerformanceCounter函數(shù)來測量時間和性能,需要進行以下步驟:
#include <Windows.h>
LARGE_INTEGER start, end, frequency;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
執(zhí)行需要計時的代碼。
調(diào)用QueryPerformanceCounter函數(shù)來獲取計數(shù)器的當前值。
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);
// 執(zhí)行需要計時的代碼
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;
}
注意: