Skip to content

Instantly share code, notes, and snippets.

@eugenius1
Last active November 25, 2016 04:44
Show Gist options
  • Save eugenius1/b725e9349a97173373c8a1f481a3f87e to your computer and use it in GitHub Desktop.
Save eugenius1/b725e9349a97173373c8a1f481a3f87e to your computer and use it in GitHub Desktop.
Parallel Accumulate using tbb::parallel_reduce

Call this function the same way you would with std::accumulate:

std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = parallelAccumulate(v.begin(), v.end(), 0);

Using Intel TBB (Threading Building Blocks).

#include <numeric> // std::accumulate
#include "tbb/parallel_reduce.h"
#include "tbb/blocked_range.h"
template <class Summable, class SummableIt>
Summable parallelAccumulate(
SummableIt beginIt,
SummableIt endIt,
const Summable initial
) const {
Summable* start = &(*beginIt);
Summable* end = &(*endIt);
return tbb::parallel_reduce(
tbb::blocked_range<Summable*>(start, end), // range
initial, // identity; initial value
[](const tbb::blocked_range<Summable*>& chunk, Summable initial)->Summable {
return std::accumulate(chunk.begin(), chunk.end(), initial);
}, // function to accumulate subrange
std::plus<Summable>() // reduction operator
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment