解决问题的时间与解决问题的办法有绝对的关系,其中有时间复杂度与空间复杂度,数据结构设计的越精巧,所需时间就越短
下面分别采用此两种方法计算,并得出运行所需时间
#include <iostream>
#include<math.h>
#include<ctime>
using namespace std;
double duration;
double f1(int n, double a[], double x);
double f2(int n, double a[], double x);
int main()
{
int n=10;
clock_t start, finish;
double x;
double a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << "Please enter a number to x:" << endl;
cin >> x;
int m;
start=clock();
for (m = 0; m < 100000000; m++)
f1(n, a, x);
cout << f1(n, a, x)<<endl;
finish=clock();
double totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "f1程序的运行时间为" << totaltime << "秒!" << endl;
start = clock();
for (m = 0; m < 100000000; m++)
f2(n, a, x);
cout << f2(n, a, x)<<endl;
finish = clock();
totaltime = (finish - start) / CLOCKS_PER_SEC;
cout << "f2程序的运行时间为" << totaltime << "秒!" << endl;
return 0;
}
double f1(int n, double a[], double x)
{
double p = a[0];
for (int i = 1; i <= n; i++)
{
p = p + a[i] * pow(x, i);
}
//cout << p << endl;
return p;
}
double f2(int n, double a[], double x)
{
double p=a[n];
for (int i = n; i >0; i--)
{
p = a[n - 1] + p*x;
}
//cout << p<<endl;
return p;
}
运行结果
Please enter a number to x:
3.12
-8.09035e+066
f1程序的运行时间为61.006秒!
-8.09035e+066
f2程序的运行时间为6秒!
请按任意键继续. . .
可见前一种方法是后一种方法所需时间的10倍,当然一次运行时间非常短暂,我这是运行了10000000次得出的结果。