Advertisement
Guest User

boost::thread sample application

a guest
Dec 10th, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <boost/timer.hpp>
  3. #include <boost/thread.hpp>
  4.  
  5. using namespace std;
  6.  
  7. class Calc
  8. {
  9. private:
  10.     double *a;
  11.     int niter;
  12.     int start;
  13.     int end;
  14.     double sum;
  15. public:
  16.     Calc(double *a_ptr, const int &niter_ref, const int &start_ref, const int &end_ref)
  17.     {
  18.         a = a_ptr;
  19.         niter = niter_ref;
  20.         start = start_ref;
  21.         end = end_ref;
  22.         sum = 0.0;
  23.     }
  24.     void run()
  25.     {
  26.         double x;
  27.         for (int i = start; i < end; i++)
  28.         {
  29.             for (int j = 0; j < niter; j++)
  30.             {
  31.                 for (int k = 0; k < niter; k++)
  32.                 {
  33.                     x = sin(a[i]) * cos(a[j]) * sin(a[k]);
  34.                     sum += x;
  35.                 }
  36.             }
  37.         }
  38.     }
  39.     double Sum()
  40.     {
  41.         return sum;
  42.     }
  43. };
  44.  
  45. double single_thread(double a[], const int &niter)
  46. {
  47.     double sum = 0.0;
  48.     double x;
  49.     for (int i = 0; i < niter; i++)
  50.     {
  51.         for (int j = 0; j < niter; j++)
  52.         {
  53.             for (int k = 0; k < niter; k++)
  54.             {
  55.                 x = sin(a[i]) * cos(a[j]) * sin(a[k]);
  56.                 sum += x;
  57.             }
  58.         }
  59.     }
  60.     return sum;
  61. }
  62.  
  63. int main()
  64. {
  65.     boost::timer t;
  66.     const int niter = 2000;
  67.     double a [niter];
  68.     double sum = 0;
  69.     for (long i = 0; i < niter; i++)
  70.     {
  71.         a[i] = (double)i / (double)niter;
  72.     }
  73.  
  74.     t.restart();
  75.     sum = single_thread(a, niter);
  76.     cout << "Serial. Sum: " << sum << " time: " << t.elapsed() << endl;
  77.  
  78.     Calc c1(a, niter, 0, niter / 2);
  79.     Calc c2(a, niter, niter / 2, niter);
  80.  
  81.     t.restart();
  82.     boost::thread calculationThread1(boost::bind( &Calc::run, &c1 ));
  83.     boost::thread calculationThread2(boost::bind( &Calc::run, &c2 ));
  84.     calculationThread1.join();
  85.     calculationThread2.join();
  86.     cout << "Two boost threads. Sum: " << c1.Sum() + c2.Sum() << " time: " << t.elapsed() << endl;
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement