clock() / CLOCKS_PER_SEC,单位为秒。
clock()函数返回进程运行时间,但是这个运行时间单位不是秒,而是CPU运行的时钟周期计数。CLOCKS_PER_SEC是标准c的time.h头函数中宏定义的一个常数,表示一秒钟内CPU运行的时钟周期数(时钟频率)。
1到n的阶乘之和
#include <stdio.h>
#include <time.h>
int main()
{
const int mod=1000000;
int n,s=0;
scanf("%d",&n);
if(n>25) n=25;
int i;
for(i=1;i<=n;i++)
{
int j,f=1;
for(j=1;j<=i;j++)
{
f=(f*j%mod);
}
s=(s+f)%mod;
}
printf("%d\n",s);
printf("time user=%.2f\n",(double)clock()/CLOCKS_PER_SEC);
return 0;
}
但是,使用此方法,键盘输入的时间也会被计入在内,为了避免输入数据的时间影响测试结果,可以采用一种“管道”的小技巧。
在命令行打开C文件所在目录,然后输入 echo n|m,其中n是你要输入的数字,m是C文件的名字。