一.利用"时钟打点"clock()函数来会比较不同算法的效率。
clock():捕捉从程序开始运行到clock()被调用时所耗费的时间。这个
时间单位是clock tick,即“时钟打点”。
常数CLK_TCK(或CLOCKS_PER_SEC):机器时钟每秒所走的时钟打点数。
#include <stdio.h>
#include <time.h>
#include <math.h>
clock_t start, stop;
double duration;
#define MAXN 10 /* 多项式最大项数,即多项式阶数+1 */
double f1(int n, double a[], double x);
double f2(int n, double a[], double x);
int main()
{
int i;
double a[MAXN]; /* 存储多项式的系数 */
for (i = 0; i < MAXN; i++) a[i] = (double)i;
start = clock();
f1(MAXN - 1, a, 1.1);
stop = clock();
duration = ((double)(stop - start)) / CLK_TCK;
printf("ticks1 = %f\n", (double)(stop - start));
printf("duration1 = %6.2e\n", duration);
start = clock();
f2(MAXN - 1, a, 1.1);
stop = clock();
duration = ((double)(stop - start)) / CLK_TCK;
printf("ticks2 = %f\n", (double)(stop - start));
printf("duration2 = %6.2e\n", duration);
return 0;
}
double f1(int n, double a[], double x)//直接计算
{
int i;
double p = a[0];
for (i = 1; i <= n; i++);
p += (a[i] * pow(x, i));
return p;
}
double f2(int n, double a[], double x)//秦九韶算法
{
int i;
double p = a[n];
for (i = n;i >= 1; i--)
p += a[i-1] + x*p;
return p;
}
f1:
f2:
在x=1.1处的值。
运行结果:
二.