Last active
December 24, 2017 06:04
-
-
Save Liam0205/a6e25c9db1956a1dbf75c915e39e6582 to your computer and use it in GitHub Desktop.
A demo show for parallem_sum of hyper_sum by using of std::async.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <future> | |
template <typename IntT, typename UnaryFunc> | |
IntT do_hyper_sum(const IntT begin, const IntT end, const UnaryFunc func) { | |
IntT res = 0; | |
for (IntT i = begin; i != end; ++i) { | |
res += func(i); | |
} | |
return std::move(res); | |
} | |
template <typename IntT, typename UnaryFunc> | |
IntT do_hyper_sum_parallel(const IntT begin, const IntT end, const UnaryFunc func) { | |
static const constexpr size_t kParallelThrd = 100; | |
const size_t diff = end - begin; | |
if (diff <= kParallelThrd) { | |
return do_hyper_sum(begin, end, func); | |
} | |
const IntT mid = begin + diff / 2; | |
auto handler = std::async(std::launch::async, do_hyper_sum_parallel<IntT, UnaryFunc>, mid, end, func); | |
const IntT res = do_hyper_sum_parallel(begin, mid, func); | |
return std::move(res + handler.get()); | |
} | |
template <typename IntT, typename UnaryFunc> | |
bool hyper_sum(const IntT begin, const IntT end, const UnaryFunc func, IntT* const res) { | |
if (not(begin < end)) { return false; } | |
if (nullptr == res) { return false; } | |
*res = do_hyper_sum_parallel(begin, end, func); | |
return true; | |
} | |
int main() { | |
using IntT = long long int; | |
IntT begin = 1; | |
IntT end = 1000; | |
IntT res = 0; | |
auto func = [](const IntT num){ return num * num + num * num * num; }; | |
if (hyper_sum(begin, end, func, &res)) { | |
std::cout << res << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On *nix, please make sure that you compile this snippet of code by