C语言计算程序运行的时间
1.概念
- 函数 clock():捕捉从程序开始运行到 clock() 被调用时所耗费的时间。这个时间的单位是clock tick,即“时钟打点”。(C语言提供的函数,使用时要引入头文件time.h 即#include<time.h>)
- 常数 CLK_TCK:机器时钟每秒所走的始终打点数。具体数值多少因机器而异。
2.常用模板
#include<stdio.h>
#include<time.h>`
clock_t start, stop;
//clock_t是clock()函数返回值的数据变量类型
double duration;
//记录被测函数的运行时间,以秒为单位
int main()
{
//不在测试范围内的准备工作写在clock()调用之前
start = clock(); //开始计时
MyFunction(); //把被测函数添加在这里
stop = clock(); //结束计时
duration = ((double)(stop - start)) / CLK_TCK;
//其他不在测试范围内的处理写在后面,例如输出duration的值
return 0;
}
3.以两种算法计算多项式值为例
利用clock()函数比较算法效率
此前,我们先来看一下下面两个公式。
f(x)=a0+a1x+…+an−1xn−1+anxnf(x)=a0+x(a1+x(…(an−1+x(an))…)) \begin{array}{l} f(x)=a_{0}+a_{1} x+\ldots+a_{n-1} x^{n-1}+a_{n} x^{n} \\ f(x)=a_{0}+x\left(a_{1}+x\left(\ldots\left(a_{n-1}+x\left(a_{n}\right)\right) \ldots\right)\right) \end{array} f(x)=a0+a1x+