forked from boostorg/compute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperf_tbb_merge.cpp
85 lines (73 loc) · 2.62 KB
/
perf_tbb_merge.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <algorithm>
#include <iostream>
#include <vector>
#include <tbb/parallel_for.h>
#include "perf.hpp"
// example from: http://www.threadingbuildingblocks.org/docs/help/reference/algorithms/parallel_for_func.htm
using namespace tbb;
template<typename Iterator>
struct ParallelMergeRange {
static size_t grainsize;
Iterator begin1, end1; // [begin1,end1) is 1st sequence to be merged
Iterator begin2, end2; // [begin2,end2) is 2nd sequence to be merged
Iterator out; // where to put merged sequence
bool empty() const {return (end1-begin1)+(end2-begin2)==0;}
bool is_divisible() const {
return std::min( end1-begin1, end2-begin2 ) > grainsize;
}
ParallelMergeRange( ParallelMergeRange& r, split ) {
if( r.end1-r.begin1 < r.end2-r.begin2 ) {
std::swap(r.begin1,r.begin2);
std::swap(r.end1,r.end2);
}
Iterator m1 = r.begin1 + (r.end1-r.begin1)/2;
Iterator m2 = std::lower_bound( r.begin2, r.end2, *m1 );
begin1 = m1;
begin2 = m2;
end1 = r.end1;
end2 = r.end2;
out = r.out + (m1-r.begin1) + (m2-r.begin2);
r.end1 = m1;
r.end2 = m2;
}
ParallelMergeRange( Iterator begin1_, Iterator end1_,
Iterator begin2_, Iterator end2_,
Iterator out_ ) :
begin1(begin1_), end1(end1_),
begin2(begin2_), end2(end2_), out(out_)
{}
};
template<typename Iterator>
size_t ParallelMergeRange<Iterator>::grainsize = 1000;
template<typename Iterator>
struct ParallelMergeBody {
void operator()( ParallelMergeRange<Iterator>& r ) const {
std::merge( r.begin1, r.end1, r.begin2, r.end2, r.out );
}
};
template<typename Iterator>
void ParallelMerge( Iterator begin1, Iterator end1, Iterator begin2, Iterator end2, Iterator out ) {
parallel_for(
ParallelMergeRange<Iterator>(begin1,end1,begin2,end2,out),
ParallelMergeBody<Iterator>(),
simple_partitioner()
);
}
int main(int argc, char *argv[])
{
perf_parse_args(argc, argv);
std::cout << "size: " << PERF_N << std::endl;
std::vector<int> v1 = generate_random_vector<int>(PERF_N / 2);
std::vector<int> v2 = generate_random_vector<int>(PERF_N / 2);
std::vector<int> v3(PERF_N);
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
perf_timer t;
for(size_t trial = 0; trial < PERF_TRIALS; trial++){
t.start();
ParallelMerge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
t.stop();
}
std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl;
return 0;
}