测量函数运行时间的clock()函数
clock():捕捉从程序开始运行到clock()被调用时所消耗的时间。这个时间单位是clock tick(时钟打点)
常数CLK_TCK:机器时钟每秒所走的时钟打点数
#include<stdio.h>
#include<time.h>
clock_t start,stop; //clock_t是clock()函数返回的变量类型
double duration; //记录被测函数运行的时间,以秒为单位
void PrintN(int n)
{
int i;
for(i=1;i<=n;i++)
{
printf("%d ",i);
}
}
main()
{
int n;
printf("请输入一个数");
scanf("%d",&n);
start = clock();//开始计时
PrintN(n); //被测的函数
stop = clock();//停止计时
duration = ((double)(stop - start))/CLK_TCK; //计算调用PrintN函数所用的时间
printf("%e",duration); //%e表示数据类型为浮点数,且用科学计算法表示
}
还没有评论,来说两句吧...