本實例演示如何使用 clock() 函數測量一段代碼(此處為 1000 萬次空循環)的 CPU 執行時間。
clock_t 類型變量 start、finish 分別記錄循環前後的時鐘計數。CLOCKS_PER_SEC 得到秒數。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
long i = 10000000L;
clock_t start, finish;
double TheTimes;
printf("做%ld次空循環需要的時間為", i);
start = clock();
while (i--);
finish = clock();
TheTimes = (double)(finish - start) / CLOCKS_PER_SEC;
printf("%f秒。\n", TheTimes);
return 0;
}
做10000000次空循環需要的時間為0.025367秒。
clock() 返回的是進程佔用的 CPU 時間,而非牆鐘時間。