步驟如下:
1.引入頭文件:
#include <time.h> 或者 #include <ctime>
2.定義:
clock_t start1,end1; //clock_t是用來保存時間的數據類型
3.把start放在想測試運行時間的那一部分前:
start1 = clock(); //clock()函數表示返回處理器調用某個進程或函數所花費的時間
4.把end放在那一部分后面:
end1 = clock();
5.計算差值:
double runtime = (double) (end1 - start) / CLOCKS_PER_SEC //CLOCKS_PER_SEC是常量:1000 ,注意這里關於時間的單位都為毫秒(ms)
(這里是進行秒的換算,如果想用毫秒作單位的話,可以不除以CLOCKS_PER_SEC)
6.最后輸出 runtime 的值:
printf("runtime = %ds", runtime);
p.s:
為什么要用double定義runtime?
runtime可能是非常小的,用int定義極易得到0。
測試代碼及其數據如下:
題目:輸出所有形如aabb的四位平方數(7744問題)(即前兩位數字相等,后兩位數字相等)
代碼如下:
#include <stdio.h> #include <time.h> //頭文件 #include <math.h> clock_t start1, end1; //定義 int main() { start1=clock(); //測試for循環的時間,開始 for(int a = 1; a <= 9; a++) { for(int b = 0; b <= 9; b++) { int n = a * 1000 + a * 100 + b * 10 + b; int c = sqrt(n); if(c == sqrt(n)) //判斷開方n是否為整數 printf("%d\n", n); } } end1=clock(); //測試for循環的時間,結束 double runtime =(double) (end1 - start1) / CLOCKS_PER_SEC; printf("runtime = %lfs\n",runtime); printf("runtime = %.3lfms\n",runtime*1000); return 0; }
輸出結果如下:
7744 runtime = 0.000013s runtime = 0.013ms