14 #ifndef NANOVDB_REDUCE_H_HAS_BEEN_INCLUDED 15 #define NANOVDB_REDUCE_H_HAS_BEEN_INCLUDED 19 #ifdef NANOVDB_USE_TBB 20 #include <tbb/parallel_reduce.h> 40 template <
typename RangeT,
typename T,
typename FuncT,
typename JoinT>
41 inline T
reduce(RangeT range,
const T& identity,
const FuncT &func,
const JoinT &join)
43 if (range.empty())
return identity;
44 #ifdef NANOVDB_USE_TBB 45 return tbb::parallel_reduce(range, identity, func, join);
46 #else// naive and likely slow alternative based on std::future 47 if (
const size_t threadCount = std::thread::hardware_concurrency()>>1) {
48 std::vector<RangeT> rangePool{ range };
49 while(rangePool.size() < threadCount) {
50 const size_t oldSize = rangePool.size();
51 for (
size_t i = 0; i < oldSize && rangePool.size() < threadCount; ++i) {
52 auto &r = rangePool[i];
53 if (r.is_divisible()) rangePool.push_back(RangeT(r,
Split()));
55 if (rangePool.size() == oldSize)
break;
57 std::vector< std::future<T> > futurePool;
58 for (
auto &r : rangePool) {
59 auto task = std::async(std::launch::async, [&](){
return func(r, identity);});
60 futurePool.push_back( std::move(task) );
63 for (
auto &f : futurePool) {
64 result = join(result, f.get());
68 return static_cast<T
>(func(range, identity));
75 template <
typename T,
typename FuncT,
typename JoinT >
76 inline T
reduce(
size_t begin,
size_t end,
size_t grainSize,
const T& identity,
const FuncT& func,
const JoinT& join)
78 Range1D range(begin, end, grainSize);
79 return reduce( range, identity, func, join );
83 template <
template<
typename...>
class ContainerT,
typename... ArgT,
typename T,
typename FuncT,
typename JoinT >
84 inline T
reduce(
const ContainerT<ArgT...> &c,
const T& identity,
const FuncT& func,
const JoinT& join)
87 return reduce( range, identity, func, join );
92 template <
template<
typename...>
class ContainerT,
typename... ArgT,
typename T,
typename FuncT,
typename JoinT >
93 inline T
reduce(
const ContainerT<ArgT...> &c,
size_t grainSize,
const T& identity,
const FuncT& func,
const JoinT& join)
95 Range1D range(0, c.size(), grainSize);
96 return reduce( range, identity, func, join );
101 #endif // NANOVDB_REDUCE_H_HAS_BEEN_INCLUDED Definition: NanoVDB.h:184
Custom Range class that is compatible with the tbb::blocked_range classes.
T reduce(RangeT range, const T &identity, const FuncT &func, const JoinT &join)
Definition: Reduce.h:41