多項式演算法效率對比
阿新 • • 發佈:2019-01-27
#include <iostream> #include <time.h> using namespace std; #define maxn 10 #define maxk 1e6 //f1、f2太小 執行時間不到一個tick //clock函式捕捉不到 所以重複跑幾次 函式重複次數 double duration; clock_t start, stop; double f1(int n,double a[],double x) { double p = a[0]; for (int i = 0; i <=n; i++) { p += a[i] * pow(x, i); } return p; } double f2(int n, double a[], double x) //秦九韶 多項式簡化演算法 { double p = a[n]; for (int i = n; i >=0; i--) { p = a[i - 1] + x * p; } return p; } int main() { double a[maxn],x=6; for (int i = 0; i < maxn; i++) { a[i] = i; } start = clock(); for (int i = 0; i < maxk; i++) { f1(maxn - 1, a, x); } stop = clock(); duration = (double)(stop - start) / CLK_TCK / maxk; printf("tick1=%f\n", (double)(stop - start)); printf("dura1=%6.2e\n", duration); start = clock(); for (int i = 0; i < maxk; i++) { f2(maxn - 1, a, x); } stop = clock(); duration = (double)(stop - start) / CLK_TCK / maxk; printf("tick2=%f\n", (double)(stop - start)); printf("dura2=%6.2e\n", duration); return 0; }