// Ex1121.cc § 11.2.1 // Calculates a polynom at point x in two different ways // and compare the execution time // Try also option -O or -Ofast in compilation // SGI : CC -Ofast Polynom.cc -lfastm // LINUX : g++ -O3 Polynom.cc // also g++ -O3 -ffast-math Polynom.cc // a.out < input.1121 #include #include // contains clock() #include int main() { const int NRUN = 100000; // number of test runs const int N = 20; // highest degree in polynom double a[N+1]; // (N+1) coefficients double x,xk,s1,s2; int k,j; double time1=0.0, time2=0.0, tstart; // time measurment cout << endl; cout << "Polynom calculation" << endl; cout << " Read coeff" << endl; for ( k = 0; k <= N; k++ ) { cin >> a[k]; } cout << endl; cout << " Read X" << endl; cout << " x = "; cin >> x; cout << endl; // version a (slow) tstart = clock(); for (j=1; j<=NRUN; j++) { s1 = 0.0; for ( k = 0; k <= N; k++) { xk = pow(x,k); s1 += xk * a[k]; } } time1 += clock()-tstart; // version b (fast) tstart = clock(); for (j=1; j<=NRUN; j++) { s2 = a[0]; xk = 1.0; for ( k = 1; k <= N; k++) { xk *= x; s2 += xk * a[k]; } } time2 += clock()-tstart; // Rescale to get seconds time1 = time1/CLOCKS_PER_SEC; time2 = time2/CLOCKS_PER_SEC; cout << " s1 = " << s1 << " (" << time1 << " sec.)" << endl; cout << " s2 = " << s2 << " (" << time2 << " sec.)" << endl; cout << endl; }