测试程序运行时间的方法——clock()
一、 步骤
-
引入头文件:
#include <time.h>或者#include <ctime> -
定义:
clock_t start1, end1(clock_t是用来保存时间的数据类型)
-
把start放在测试程序结束前:
start1 = clock(); -
把end放在测试程序结束处:
end1 = clock(); -
计算时间差:
double runtime = (double) (end1 - start1) / CLOCKS_PER_SEC(CLOCK_PER_SEC是常量:1000,计算出的runtime时间为毫秒(ms),如果想用毫秒作单位,不除以CLOCK_PER_SEC即可)
-
最后输出runtime的值:
print("runtime = %ds\n", runtime);
二、 测试代码及数据
- 题目:输出所有形如aabb的四位平方数(7744)问题(即前两位数字相等,后两位数字相等)
- 代码部分:
#include <stdio.h>
#include <time.h> //头文件
#include <math.h>
clock_t start1, end1; //定义
int main()
{
start1=clock(); //测试for循环的时间,开始
for(int a = 1; a <= 9; a++)
{
for(int b = 0; b <= 9; b++)
{
int n = a * 1000 + a * 100 + b * 10 + b;
int c = sqrt(n);
if(c == sqrt(n)) //判断开方n是否为整数
printf("%d\n", n);
}
}
end1=clock(); //测试for循环的时间,结束
double runtime =(double) (end1 - start1) / CLOCKS_PER_SEC;
printf("runtime = %lfs\n",runtime);
printf("runtime = %.3lfms\n",runtime*1000);
return 0;
}
- 输出结果
7744
runtime = 0.000013s
runtime = 0.013ms

浙公网安备 33010602011771号