Advertisement
gaurish108

Untitled

Jan 31st, 2012
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. // f(x) = 4/(1+x^2)
  2. // Domain of integration: [0,1]
  3. // Integral over the domain = pi =(approx) 3.14159
  4.  
  5. #include <iostream>
  6. #include <omp.h>
  7. #include <vector>
  8. #include <algorithm>
  9. #include <functional>
  10. #include <numeric>
  11.  
  12.  
  13. int main (void)
  14. {
  15.   //Information common to serial and parallel computation.
  16.   int    num_steps = 2e7;
  17.   double dx        = 1.0/num_steps;
  18.  
  19.  
  20.  
  21.   //Serial Computation
  22.    double start = omp_get_wtime();
  23.  
  24.    double serial_sum = 0;
  25.    double x          = 0;
  26.    for (int i=0;i< num_steps; ++i)
  27.       {
  28.          serial_sum += 4.0*dx/(1.0+x*x);
  29.               x += dx;
  30.      }
  31.  
  32.     double end = omp_get_wtime();
  33.     std::cout << "Time taken for the serial computation: "      << end-start         << " seconds";
  34.     std::cout << "\t\tPi serial: "                              << serial_sum        <<   std::endl;
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.    //OpenMP computation. Method of integration, just a plain Riemann sum
  43.     std::cout << "How many OpenMP threads do you need for parallel computation? ";
  44.     int t;//number of openmp threads
  45.     std::cin >> t;
  46.  
  47.     start  = omp_get_wtime();
  48.     double  parallel_sum = 0; //will be modified atomically
  49.     #pragma omp parallel num_threads(t)
  50.     {
  51.       int threadIdx = omp_get_thread_num();
  52.       int begin = threadIdx * num_steps/t; //integer index of left end point of subinterval
  53.       int end   = begin + num_steps/t;   // interger index of right-endpoint of sub-interval
  54.       double dx_local = dx;
  55.       double temp = 0;
  56.       double x    = begin*dx;
  57.  
  58.       for (int i = begin; i < end; ++i)
  59.     {    
  60.          temp += 4.0*dx_local/(1.0+x*x);
  61.          x    += dx_local;
  62.     }
  63.      #pragma omp atomic
  64.       parallel_sum += temp;
  65.      }
  66.     end   = omp_get_wtime();
  67.     std::cout << "Time taken for the parallel computation: "    << end-start << " seconds";
  68.     std::cout << "\tPi parallel: "                                << parallel_sum        <<   std::endl;
  69.    
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement