perf_tbb_accumulate.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  4. // Distributed under the Boost Software License, Version 1.0
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #include <algorithm>
  11. #include <iostream>
  12. #include <numeric>
  13. #include <vector>
  14. #include <tbb/blocked_range.h>
  15. #include <tbb/parallel_reduce.h>
  16. #include "perf.hpp"
  17. int rand_int()
  18. {
  19. return static_cast<int>((rand() / double(RAND_MAX)) * 25.0);
  20. }
  21. template<class T>
  22. struct Sum {
  23. T value;
  24. Sum() : value(0) {}
  25. Sum( Sum& s, tbb::split ) {value = 0;}
  26. void operator()( const tbb::blocked_range<T*>& r ) {
  27. T temp = value;
  28. for( T* a=r.begin(); a!=r.end(); ++a ) {
  29. temp += *a;
  30. }
  31. value = temp;
  32. }
  33. void join( Sum& rhs ) {value += rhs.value;}
  34. };
  35. template<class T>
  36. T ParallelSum( T array[], size_t n ) {
  37. Sum<T> total;
  38. tbb::parallel_reduce( tbb::blocked_range<T*>( array, array+n ),
  39. total );
  40. return total.value;
  41. }
  42. int main(int argc, char *argv[])
  43. {
  44. perf_parse_args(argc, argv);
  45. std::cout << "size: " << PERF_N << std::endl;
  46. // create vector of random numbers on the host
  47. std::vector<int> host_vector(PERF_N);
  48. std::generate(host_vector.begin(), host_vector.end(), rand_int);
  49. int sum = 0;
  50. perf_timer t;
  51. for(size_t trial = 0; trial < PERF_TRIALS; trial++){
  52. t.start();
  53. sum = ParallelSum<int>(&host_vector[0], host_vector.size());
  54. t.stop();
  55. }
  56. std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl;
  57. std::cout << "sum: " << sum << std::endl;
  58. int host_sum = std::accumulate(host_vector.begin(), host_vector.end(), int(0));
  59. if(sum != host_sum){
  60. std::cerr << "ERROR: sum (" << sum << ") != (" << host_sum << ")" << std::endl;
  61. return -1;
  62. }
  63. return 0;
  64. }