C語言使用clock進行計時


  1. #include “stdio.h”  
  2. #include “stdlib.h”  
  3. #include “time.h”  
  4.   
  5. int main( void )  
  6. {  
  7.    long    i = 10000000L;  
  8.    clock_t start, finish;  
  9.    double  duration;  
  10.      
  11.    printf( "Time to do %ld empty loops is ", i );  
  12.    start = clock();  
  13.    while( i-- )      ;  
  14.    finish = clock();  
  15.    duration = (double)(finish - start) / CLOCKS_PER_SEC;  
  16.    printf( "%f seconds\n", duration );  
  17.    system("pause");  

  18. 現在是分析代碼,首先是用到clock,其實就是利用時鍾周期的意思,到底是怎么計算的呢?基本思想就是計算到底代碼的運行花費了多少時鍾周期,然后再除以每一秒所花費的時鍾周期數目,記住,單位是秒,從結果上看也很容易得出基本單位是毫秒。

  19. 首先定義 clock_t start,變量,記錄所花費的時鍾周期數目,然后再轉換成時間間隔,基本上思想就是這樣。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM