/* =========================================================== compute Pi by integrating the function 1/SQRT(1-x^2) OpenMP version 2: using parallel for =========================================================== */ using namespace std; #include #include #include #include #include double f(double a) { return( 2.0 / sqrt(1 - a*a) ); } /* ======================= MAIN ======================= */ int main(int argc, char *argv[]) { int N; double pi; double w; // Width of rectangle struct timeval start_time, stop_time; int elapsed; /* ----- Check command line ----- */ if ( argc != 2 ) { cout << "Usage: " << argv[0] << " Num_Intervals" << endl; exit(1); } /* ----- Get number of intervals and number of threads ----- */ N = atoi(argv[1]); w = 1.0/(double) N; pi = 0.0; /* ================================================== Calaculate pi by adding area of rectangles ================================================== */ gettimeofday(&start_time, NULL); // Check start time #pragma omp parallel { int i; double x; double my_pi; #pragma omp for for (i = 0; i < N; i = i + 1) { x = (i + 0.5)*w; my_pi = my_pi + w*f(x); } #pragma omp critical { pi = pi + my_pi; } } gettimeofday(&stop_time, NULL); // Check stop time cout << "Computed Pi = " << pi << endl << endl; elapsed = (stop_time.tv_sec*1000000 + stop_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec); cout << "Elapsed time = " << elapsed << " microseconds" << endl; }