测试程序运行时间的方法——clock()

步骤如下:

1.引入头文件
        #include <time.h> 或者 #include <ctime>

2.定义

        clock_t start1,end1;                  //clock_t是用来保存时间的数据类型

3.把start放在想测试运行时间的那一部分前
        start1 = clock();                        //clock()函数表示返回处理器调用某个进程或函数所花费的时间

4.把end放在那一部分后面

        end1 = clock();

5.计算差值

       double runtime =  (double) (end1 - start) / CLOCKS_PER_SEC           //CLOCKS_PER_SEC是常量:1000 ,注意这里关于时间的单位都为毫秒(ms)

      (这里是进行秒的换算,如果想用毫秒作单位的话,可以不除以CLOCKS_PER_SEC)

6.最后输出 runtime 的值

       printf("runtime =  %ds", runtime);

p.s:

为什么要用double定义runtime?

       runtime可能是非常小的,用int定义极易得到0

 

测试代码及其数据如下:

       题目:输出所有形如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

猜你喜欢

转载自www.cnblogs.com/PlayfulBlueMoon/p/12232907.html