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