Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <boost/timer.hpp>
- #include <boost/thread.hpp>
- using namespace std;
- class Calc
- {
- private:
- double *a;
- int niter;
- int start;
- int end;
- double sum;
- public:
- Calc(double *a_ptr, const int &niter_ref, const int &start_ref, const int &end_ref)
- {
- a = a_ptr;
- niter = niter_ref;
- start = start_ref;
- end = end_ref;
- sum = 0.0;
- }
- void run()
- {
- double x;
- for (int i = start; i < end; i++)
- {
- for (int j = 0; j < niter; j++)
- {
- for (int k = 0; k < niter; k++)
- {
- x = sin(a[i]) * cos(a[j]) * sin(a[k]);
- sum += x;
- }
- }
- }
- }
- double Sum()
- {
- return sum;
- }
- };
- double single_thread(double a[], const int &niter)
- {
- double sum = 0.0;
- double x;
- for (int i = 0; i < niter; i++)
- {
- for (int j = 0; j < niter; j++)
- {
- for (int k = 0; k < niter; k++)
- {
- x = sin(a[i]) * cos(a[j]) * sin(a[k]);
- sum += x;
- }
- }
- }
- return sum;
- }
- int main()
- {
- boost::timer t;
- const int niter = 2000;
- double a [niter];
- double sum = 0;
- for (long i = 0; i < niter; i++)
- {
- a[i] = (double)i / (double)niter;
- }
- t.restart();
- sum = single_thread(a, niter);
- cout << "Serial. Sum: " << sum << " time: " << t.elapsed() << endl;
- Calc c1(a, niter, 0, niter / 2);
- Calc c2(a, niter, niter / 2, niter);
- t.restart();
- boost::thread calculationThread1(boost::bind( &Calc::run, &c1 ));
- boost::thread calculationThread2(boost::bind( &Calc::run, &c2 ));
- calculationThread1.join();
- calculationThread2.join();
- cout << "Two boost threads. Sum: " << c1.Sum() + c2.Sum() << " time: " << t.elapsed() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement