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

一、 步骤
  1. 引入头文件:

    #include <time.h> 或者#include <ctime>

  2. 定义:

    clock_t start1, end1

    (clock_t是用来保存时间的数据类型)

  3. 把start放在测试程序结束前:

    start1 = clock();

  4. 把end放在测试程序结束处:

    end1 = clock();

  5. 计算时间差:

    double runtime = (double) (end1 - start1) / CLOCKS_PER_SEC

    (CLOCK_PER_SEC是常量:1000,计算出的runtime时间为毫秒(ms),如果想用毫秒作单位,不除以CLOCK_PER_SEC即可)

  6. 最后输出runtime的值:

    print("runtime = %ds\n", runtime);

二、 测试代码及数据
  1. 题目:输出所有形如aabb的四位平方数(7744)问题(即前两位数字相等,后两位数字相等)
  2. 代码部分:
#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;
}
  1. 输出结果
7744
runtime = 0.000013s
runtime = 0.013ms
posted @ 2020-01-25 11:27  Maple1234  阅读(1729)  评论(0)    收藏  举报