fork download
  1. // parallel_for.cpp
  2. // compilation: g++ -O3 -std=c++0x parallel_for.cpp -o parallel_for -lpthread
  3. // execution: time ./parallel_for 100 50000000
  4. // (100: number of threads, 50000000: vector size)
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <cstdlib>
  8. #include <vector>
  9. #include <thread>
  10. #include <cmath>
  11. #include <algorithm>
  12. #include <numeric>
  13. #include <utility>
  14.  
  15. // Parallel for
  16. template<typename Iterator, class Function>
  17. void parallel_for(const Iterator& first, const Iterator& last, Function f, const int nthreads = 1, const int threshold = 100)
  18. {
  19. const unsigned int group = std::max(std::max(1, std::abs(threshold)), (last-first)/std::abs(nthreads));
  20. std::vector<std::thread> threads;
  21. for (Iterator it = first; it < last; it += group) {
  22. threads.push_back(std::thread([=, &f](){std::for_each(it, std::min(it+group, last), f);}));
  23. }
  24. std::for_each(threads.begin(), threads.end(), [](std::thread& x){x.join();});
  25. }
  26.  
  27. // Function to apply
  28. template<typename Type>
  29. void f(Type& x)
  30. {
  31. x = std::sin(x)+std::exp(std::cos(x))/std::exp(std::sin(x));
  32. }
  33.  
  34. // Main
  35. int main(int argc, char* argv[]) {
  36.  
  37. const unsigned int nthreads = (argc > 1) ? std::atol(argv[1]) : (7);
  38. const unsigned int n = (argc > 2) ? std::atol(argv[2]) : (1000);
  39. double x = 0;
  40. double y = 0;
  41. std::vector<double> v(n);
  42.  
  43. std::iota(v.begin(), v.end(), 0);
  44. std::for_each(v.begin(), v.end(), f<double>);
  45. for (unsigned int i = 0; i < n; ++i) x += v[i];
  46.  
  47. std::iota(v.begin(), v.end(), 0);
  48. parallel_for(v.begin(), v.end(), f<double>, nthreads);
  49. for (unsigned int i = 0; i < n; ++i) y += v[i];
  50.  
  51. std::cout<<std::setprecision(15)<<x<<" "<<y<<std::endl;
  52. return 0;
  53. }
  54.  
  55.  
Success #stdin #stdout 0s 35816KB
stdin
Standard input is empty
stdout
1567.22616587821 1567.22616587821