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
11 #include <algorithm>
12 #include <iostream>
13 #include <numeric>
14 #include <vector>
15
16 #include <tbb/blocked_range.h>
17 #include <tbb/parallel_reduce.h>
18
19 #include "perf.hpp"
20
rand_int()21 int rand_int()
22 {
23 return static_cast<int>((rand() / double(RAND_MAX)) * 25.0);
24 }
25
26 template<class T>
27 struct Sum {
28 T value;
SumSum29 Sum() : value(0) {}
SumSum30 Sum( Sum& s, tbb::split ) {value = 0;}
operator ()Sum31 void operator()( const tbb::blocked_range<T*>& r ) {
32 T temp = value;
33 for( T* a=r.begin(); a!=r.end(); ++a ) {
34 temp += *a;
35 }
36 value = temp;
37 }
joinSum38 void join( Sum& rhs ) {value += rhs.value;}
39 };
40
41 template<class T>
ParallelSum(T array[],size_t n)42 T ParallelSum( T array[], size_t n ) {
43 Sum<T> total;
44 tbb::parallel_reduce( tbb::blocked_range<T*>( array, array+n ),
45 total );
46 return total.value;
47 }
48
main(int argc,char * argv[])49 int main(int argc, char *argv[])
50 {
51 perf_parse_args(argc, argv);
52 std::cout << "size: " << PERF_N << std::endl;
53
54 // create vector of random numbers on the host
55 std::vector<int> host_vector(PERF_N);
56 std::generate(host_vector.begin(), host_vector.end(), rand_int);
57
58 int sum = 0;
59 perf_timer t;
60 for(size_t trial = 0; trial < PERF_TRIALS; trial++){
61 t.start();
62 sum = ParallelSum<int>(&host_vector[0], host_vector.size());
63 t.stop();
64 }
65 std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl;
66 std::cout << "sum: " << sum << std::endl;
67
68 int host_sum = std::accumulate(host_vector.begin(), host_vector.end(), int(0));
69 if(sum != host_sum){
70 std::cerr << "ERROR: sum (" << sum << ") != (" << host_sum << ")" << std::endl;
71 return -1;
72 }
73
74 return 0;
75 }
76