使用 C 標準庫 <ctime> 的 clock() 取得處理器時脈數,除以 CLOCKS_PER_SEC 換算秒數。
#include <iostream>
#include <ctime>
void do_something() {
for (int i = 0; i < 100000; ++i)
for (int j = 0; j < 10000; ++j)
; // 空迴圈
}
int main() {
clock_t start = clock();
do_something();
clock_t end = clock();
double time = static_cast<double>(end - start) / CLOCKS_PER_SEC;
cout << "time = " << time << endl;
return 0;
}
clock() 回傳處理器時間,非牆鐘時間;多執行緒程式會累加所有執行緒 CPU 時間。<chrono>(steady_clock、high_resolution_clock)。benchmark 框架(Google Benchmark 等)。