#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 #include using namespace std; void print_time(const string& heading, const double& t) { cout << heading << " : "; cout.width(10);cout.precision(6); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout << t << endl; } void format_20_16() { cout.width(20);cout.precision(16); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); } void format_08_06() { cout.width(8);cout.precision(6); cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); } 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; double cplusplus_internal_pi; double interval_width; double partial_pi; double partial_sum; double total_pi; double x; double time_difference; double* sendbuf; double* recbuf; int i; int j; int n_intervals; int error_number; int this_process; int n_processes; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &n_processes); MPI_Comm_rank(MPI_COMM_WORLD, &this_process); heading = "\n Program starts "; if (this_process == 0) { t = timer_01.elapsed(); print_time(heading, t); } n_intervals = 1000000; cplusplus_internal_pi = 4.0 * atan(1.0); if (this_process == 0) { cout << "\n C++ internal pi 4.0*atan(1.0) \n" << endl; cout << " "; format_20_16(); cout << cplusplus_internal_pi << endl; } heading = " Loop time "; for (j = 1; j < 5; j++) { interval_width = 1.0 / n_intervals; partial_sum = 0.0; for (i = this_process +1 ; i <= n_intervals; i = i + n_processes) { x = interval_width * (double(i) - 0.5); partial_sum = partial_sum + f(x); } partial_pi = interval_width * partial_sum; sendbuf = &partial_pi; recbuf = &total_pi; MPI_Reduce(sendbuf, recbuf, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (this_process == 0) { t = timer_01.elapsed(); time_difference = t; timer_01.reset(); cout << " "; cout << " N intervals "; cout.width(12); cout << n_intervals; cout << " time = "; format_08_06(); cout << time_difference << endl; cout << " Calculated "; format_20_16(); cout << total_pi << endl; cout << " Difference "; format_20_16(); cout << abs(total_pi - cplusplus_internal_pi) << endl; } n_intervals = n_intervals * 10; } if (this_process == 0) { t = timer_02.elapsed(); heading = " \n Total time "; print_time(heading, t); } MPI_Finalize(); return(0); }