c语言the clock,C语言中的clock()函数

本文介绍了如何利用C语言中的clock()函数来测量程序的运行时间。clock_t类型的clock()函数返回从程序开始到调用该函数时的处理器时钟计数,结合CLOCKS_PER_SEC常量可以将时间转换为秒。示例代码展示了如何测量一个循环执行10000000次的函数的运行时间,并输出执行时间。

clock_t clock(void)

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

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

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

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

#include

#include

int sum(int n)

{

int res = 0;

if (n < 1)

{

printf("错误!\n");

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("错误!\n");

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\n", (double)(end_time - start_time) / CLOCKS_PER_SEC);

return 0;

}

运行结果:

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值