-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallelAccumulate.hpp
60 lines (48 loc) · 2.05 KB
/
parallelAccumulate.hpp
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
#ifndef _PARALLEL_ACCUMULATE_HPP_
#define _PARALLEL_ACCUMULATE_HPP_
#include <numeric>
#include <future>
template< class InputIt, class T, class BinaryOperation >
T parallelAccumulate(InputIt first, InputIt last, T init, BinaryOperation biOp ){
int dist=std::distance(first,last);
int coreCount = std::thread::hardware_concurrency();
std::future<T> th[coreCount];
for(int i=0;i<coreCount;++i){
if(i!=coreCount-1){
th[i]=std::move(std::async(std::launch::async,[&first,&last,&biOp,coreCount,dist,i]{return std::accumulate(std::next(first,(dist*i/coreCount)),std::next(first,(dist*(i+1)/coreCount)),0,biOp);}));
}else
{
th[i]=std::move(std::async(std::launch::async,[&first,&last,&biOp,coreCount,dist,i]{return std::accumulate(std::next(first,(dist*i/coreCount)),last,0,biOp);}));
}
}
int result=0;
for(auto &val : th)
result += val.get();
return result+init;
}
template< class InputIt, class T, class BinaryOperation >
T pureParallelAccumulate(InputIt first, InputIt last, T init, BinaryOperation biOp ){ //It doesn't use std::accumulate STL function. But low performance.
auto local_accumulate = [](InputIt first,InputIt last,T init, BinaryOperation biOp){
T res{};
for(auto iter=first;iter!=last;++iter){
res+=*iter;
}
return res;
};
int dist=std::distance(first,last);
int coreCount = std::thread::hardware_concurrency();
std::future<T> th[coreCount];
for(int i=0;i<coreCount;++i){
if(i!=coreCount-1){
th[i]=std::move(std::async(std::launch::async,local_accumulate,std::next(first,(dist*i/coreCount)),std::next(first,(dist*(i+1)/coreCount)),0,biOp));
}else
{
th[i]=std::move(std::async(std::launch::async,local_accumulate,std::next(first,(dist*i/coreCount)),last,0,biOp));
}
}
int result=0;
for(auto &val : th)
result += val.get();
return result+init;
}
#endif