C语言中的clock()函数

clock_t clock(void)

返回程序执行起(一般为程序开头),处理器时钟所使用的时间。

其中,clock_t 是一个长整型,它是一个适合存储处理器时间的类型。

clock() 的实际意义是指“进程启动到调用clock()函数经过了多少CPU时钟计时单元”,借助 CLOCKS_PER_SEC 这个常量可以把 clock_t 转化为以秒为单位的数值。

用法示例,测量一个例程的运行时间:

#include <stdio.h>
#include <time.h>

int sum(int n)
{
    int res = 0;
    if (n < 1)
    {
        printf("错误!
");
        return res;
    }
    for(int i = 1; i <= n; i++)
        res += i * i;
    return res;
}

int sum2(int n)
{
    int res = 0;
    if (n < 1)
    {
        printf("错误!
");
        return res;
    }
    res = n * (n + 1) * (2 * n + 1) / 6;
    return res;
}


// 测试函数
int main()
{
    clock_t start_time, end_time;

    start_time = clock();
    for (int i = 0; i < 10000000; ++i)
    {
        sum2(1000);
    }
    end_time = clock();
    printf("执行时间为 %f s
", (double)(end_time - start_time) / CLOCKS_PER_SEC);

    return 0;
}

运行结果:

参考:

https://www.runoob.com/cprogramming/c-standard-library-time-h.html

https://www.cnblogs.com/yannanying/p/4342760.html

原文地址:https://www.cnblogs.com/fanlumaster/p/13697748.html