clock() — 毫秒級精度標準 C 庫函數,回傳處理器時鐘數,適用於一般效能分析。
#include#include int main() { clock_t start = clock(); { /* 待測試程式碼區段 */ } clock_t end = clock(); printf("執行時間: %f 秒\n", (double)(end - start) / CLOCKS_PER_SEC); return 0; }
注意:精度受限於 CLOCKS_PER_SEC(通常為 1000),約毫秒級。
QueryPerformanceCounter — 微秒級高精度Windows API,利用硬體高解析度計數器,適合精密計時。
#include#include int main() { LARGE_INTEGER nFreq, t1, t2; double dt; QueryPerformanceFrequency(&nFreq); // 取得頻率 QueryPerformanceCounter(&t1); // 起始計數 { /* 待測試程式碼區段 */ } QueryPerformanceCounter(&t2); // 結束計數 dt = (double)(t2.QuadPart - t1.QuadPart) / nFreq.QuadPart; std::cout << "執行時間: " << dt * 1000 << " ms" << std::endl; return 0; }
| 特性 | clock() | QueryPerformanceCounter |
|---|---|---|
| 精度 | 毫秒級 (~1ms) | 微秒級 (~0.001ms) |
| 可移植性 | 跨平台 (標準 C) | 僅 Windows |
| 測量對象 | CPU 時間 | 牆鐘時間 |
| 適用場景 | 粗略效能分析 | 精密基準測試、遊戲迴圈計時 |
std::chrono::high_resolution_clockQueryPerformanceCounter 測量的是實際經過時間,非 CPU 累積時間