在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;
}
注意: