#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 { double temp; temp = std::chrono::duration_cast (hi_res_clock::now() - start_timing).count(); return(temp); } double time_difference() const { double temp; temp = std::chrono::duration_cast (hi_res_clock::now() - last_time).count(); return(temp); } private: typedef std::chrono::high_resolution_clock hi_res_clock; typedef std::chrono::duration > second_; std::chrono::time_point start_timing; std::chrono::time_point last_time; }; #include #include #include #include using namespace std; void tidy_print() { cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.width(25); cout.precision(16); } void print_summary(const int & n,const double & d,const double & real_pi) { cout << " n = " ; cout.setf(ios::right); cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.width(15); cout << n << endl; tidy_print(); cout << d << endl; tidy_print(); cout << real_pi ; tidy_print(); cout << (abs(real_pi-d)) << endl; } 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; } inline double f(double x) { double f; f = 4.0/(1.0+x*x); return(f); } int main() { double cplusplus_internal_pi; double partial_pi; double openmp_pi; double width; double x; int nthreads; int i; int j; int k; int n; double t1,t2,t3; timer timer_01; timer timer_02; timer timer_03; string heading; nthreads = omp_get_max_threads(); cplusplus_internal_pi = 4.0*atan(1.0); cout << " Maximum number of threads is " << nthreads << endl; heading = "\nProgram starts"; t1=timer_01.elapsed(); t2=timer_02.elapsed(); t3=timer_03.elapsed(); print_time( heading , t1); k = 1; for(;;) { n = 100000; omp_set_num_threads(k); cout << "***********************" << endl; cout << " Number of threads = " << k << endl; cout << "***********************" << endl; heading = " Time = "; for (j = 1;j<= 5;j++) { width = 1.0/n; partial_pi = 0.0; #pragma omp parallel for private(x) shared(width) reduction(+:partial_pi) for(i = 1;i<= n;i++) { x = width*(double(i)-0.5); partial_pi = partial_pi + f(x); } openmp_pi = width*partial_pi; t1=timer_01.elapsed(); print_summary(n,openmp_pi,cplusplus_internal_pi); print_time(heading,t1); timer_01.reset(); n = n*10; } t2=timer_02.elapsed(); heading = " Thread time"; print_time(heading,t2); timer_02.reset(); k++; if (k>nthreads) goto finish; } finish:cout << " Program ends" << endl; t3=timer_03.elapsed(); heading = " Overall time" ; print_time(heading,t3); return(0); }