c語言中測試代碼的運行時間

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <time.h>  
  3. #include <windows.h>  
  4.   
  5. void main()  
  6. {  
  7.    clock_t start , finish;  
  8.   
  9.    start = clock();  
  10.    Sleep(23);  
  11.    finish = clock();  
  12.      
  13.      
  14.    double elapsed_time;  
  15.    elapsed_time = (finish - start) / (double)CLOCKS_PER_SEC;  
  16.    printf("%lf\n",elapsed_time);  
  17. }  


一、使用time.h中clock函數 windows

[cpp]  view plain copy
  1. #include "stdio.h"  
  2. #include "time.h"  
  3.   
  4. int main(int argc, char ** argv)  
  5. {  
  6.     time_t time1, time2;  
  7.     time1 = time((time_t *)NULL);  
  8.     //your code  
  9.     time2 = time((time_t *)NULL);  
  10.     printf("%f\n", difftime(time2, time2));  
  11.     return 0;  
  12. }  

二、使用time和difftime函數 app

以上這兩種方式,處理測試代碼時,結果都是0.000000,不是我想要的結果 函數

用LARGE_INTEGER查看系統運行時間,運行結果能夠達到毫秒級 測試

三、使用LARGE_INTEGER spa

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <windows.h>   // 注意,該功能須要調用windows.h  
  4.   
  5.   
  6. void main()  
  7. {  
  8.     int i;  
  9.     long sum=0;  
  10.   
  11.     double d;  
  12.     LARGE_INTEGER Freg;                  
  13.     LARGE_INTEGER Count1, Count2;  
  14.   
  15.     QueryPerformanceFrequency(&Freg);  // 調用API函數,這個API函數但是優先級0的函數啊. 獲得系統計數器頻率  
  16.         QueryPerformanceCounter(&Count1);  // 獲取時間一  
  17.   
  18.     for(i=1;i<=500;i++)   // 執行程序。  
  19.         sum=sum+i;  
  20.   
  21.     QueryPerformanceCounter(&Count2);  // 獲取時間二  
  22.     d = (double)(Count2.QuadPart - Count1.QuadPart) / (double)Freg.QuadPart * 1000.0;  
  23.     // 獲得的d爲時間差,單位爲毫秒。  
  24.   
  25.     printf("The time is %f, and the sum is %d\n",d,sum);  
  26. }  
相關文章
相關標籤/搜索