#include #include using namespace std; class timer { public: timer() : start_timing(hi_res_clock::now()) {} void reset() { start_timing = hi_res_clock::now(); } double elapsed() const { return(std::chrono::duration_cast (hi_res_clock::now() - start_timing).count()); } private: typedef std::chrono::high_resolution_clock hi_res_clock; typedef std::chrono::duration > second_; std::chrono::time_point start_timing; }; #include #include #include #include #include using namespace std; void print_time(const string & heading , const double & t) { cout << heading << " : " ; cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.width(10); cout.precision(6); cout << t << endl; } double f(double x) { double f; f = 4.0/(1.0+x*x); return(f); } int main() { timer timer_01; timer timer_02; double t; string heading; int i, j; int n_intervals; double interval_width, x, total, pi; double cplusplus_internal_pi; double time_difference; heading = "\n Program starts "; t=timer_01.elapsed(); print_time(heading , t); n_intervals = 1000000; cplusplus_internal_pi = 4.0*atan(1.0); cout << "\n C++ internal pi 4.0*atan(1.0) \n" << endl; cout << " " ; cout.width(20); cout.precision(16); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << cplusplus_internal_pi << endl; heading = " Loop time "; for(j=1;j<5;j++) { interval_width = 1.0/n_intervals; total = 0.0; for (i=1; i <= n_intervals;i++) { x = interval_width*(double(i)-0.5); total = total + f(x); } t = timer_01.elapsed(); time_difference = t; timer_01.reset(); pi = interval_width*total; cout << " "; cout << " N intervals " ; cout.width(12); cout << n_intervals ; cout << " time = " ; cout.width(8); cout.precision(6); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << time_difference << endl; cout << " Calculated " ; cout.width(20); cout.precision(16); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << pi << endl; cout << " Difference " ; cout.width(20); cout.precision(16); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << abs(pi-cplusplus_internal_pi) << endl; n_intervals = n_intervals*10; } t = timer_02.elapsed(); heading = " \n Total time "; print_time(heading,t); return(0); }