#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 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; } int main() { int openmp_sum; int int_sum; int * x; int nthreads; int i; int j; int k; int n; double t1, t2; timer timer_01; timer timer_02; string heading; nthreads = omp_get_max_threads(); cout << " Maximum number of threads is " << nthreads << endl; heading = "\nProgram starts"; t1 = timer_01.elapsed(); t2 = timer_02.elapsed(); print_time(heading, t1); k = 1; n = 100000000; x = new int[n]; int_sum = n * 1; for (i = 0; i < nthreads; i++) { omp_set_num_threads(k); openmp_sum = 0.0; cout << "***********************" << endl; cout << " Number of threads = " << k << endl; cout << "***********************" << endl; #pragma omp parallel for private(j) shared(n) shared(x) for (j = 0; j < n; j++) { x[j] = 1; } t1 = timer_01.elapsed(); heading = "Initialisation "; print_time(heading, t1); timer_01.reset(); #pragma omp parallel for private(k) shared(n) shared(x) reduction(+:openmp_sum) for (k = 0; k < n; k++) { openmp_sum += x[k]; } t1 = timer_01.elapsed(); heading = "Summation "; print_time(heading, t1); cout << int_sum << endl; cout << openmp_sum << endl; timer_01.reset(); k = k + 1; } cout << " Program ends" << endl; t2 = timer_02.elapsed(); heading = " Total time"; print_time(heading, t2); return(0); }