clock():捕捉从程序开始运行到clock()被调用时所耗费的时间。这个时间单位是clock tick ,即“时钟打点”。

常数CLK_TCK:机器时钟每秒所走的时钟打点数。

 1 #include <stdio.h>
 2 #include <time.h>
 3 
 4 colck_t start, stop;
 5 /* clock_t 是clock() 函数返回的变量类型*/
 6 
 7 double duration;
 8 /* 记录被测函数运行时间,以秒为单位*/
 9 
10 int main()
11 {
12     /*不在测试范围内的准备工作写在clock()调用之前*/
13     start = clock();        /*    开始计时    */
14     MyFunction();            /*    把被测函数加在这里    */
15     stop = clock();            /*     停止计时    */
16     duration = ((double)(stop - start))/CLK_TCK;
17 
18     /*    其他不在测试范围的处理写在后面,eg:输出duration的值*/
19 }

实验_eg:执行下面打印一次“Hello World!”的时间

     注意:因为程序执行的太快,所以显示为0;

 1 #include <stdio.h>
 2 #include <time.h>
 3 void hello();
 4 int main(){
 5     clock_t start, stop;
 6     double duration;
 7     start = clock();
 8     hello();
 9     stop = clock();
10     duration = ((double)(stop - start))/CLK_TCK;
11     printf("该程序运行的时间是:%fn",duration);
12     return 0;
13 }
14 void hello(){
15     printf("Hello World!n");
16 }

 

解决方案:让被测函数重复运行充分多次,使得测出的总的时钟打点间隔充分长,最后计算被测函数平均运行的时间。

 1 #include <stdio.h>
 2 #include <time.h>
 3 
 4 #define MAXK 1e5 /*    被测函数最大重复调用次数    */
 5 
 6 void hello();
 7 int main(){
 8     int i;
 9     clock_t start, stop;
10     double duration;
11     start = clock();
12     for(i=0; i<MAXK; i++){
13         hello();
14     }
15     stop =  clock();
16     duration = ((double)(stop - start))/CLK_TCK/MAXK;
17 
18     printf("duration = %fn",duration);//0.00003s左右
19     return 0;
20 }
21 
22 void hello(){
23     printf("Hello world!");
24 }

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!