Skip to content

Instantly share code, notes, and snippets.

@cwvh
Created May 26, 2013 04:42
Show Gist options
  • Save cwvh/5651731 to your computer and use it in GitHub Desktop.
Save cwvh/5651731 to your computer and use it in GitHub Desktop.
parallel features of C++11
#include <iostream>
#include <future>
#include <vector>
#include <algorithm>
#include <numeric>
#include <chrono>
template<typename Ran>
int parallel_sum(Ran b, Ran e)
{
typename Ran::difference_type len = e - b;
if (len < 10000000)
return std::accumulate(b, e, 0);
Ran m = b + len/2;
auto handle = std::async(std::launch::async, parallel_sum<Ran>, m, e);
const int sum = parallel_sum(b, m);
return sum + handle.get();
}
template<typename Cont>
void run(const Cont& vs, std::function<int()> f)
{
using namespace std::chrono;
time_point<system_clock> start, end;
start = system_clock::now();
const int result = f();
end = system_clock::now();
const int elapsed_ms = duration_cast<milliseconds>(end-start).count();
std::cout << "result=" << result << " (" << elapsed_ms << "ms)\n";
}
int main(int argc, char** argv)
{
const int n = argc>1 ? std::stoi(argv[1]) : 100;
std::vector<int> v(n, 1);
run(v, [&v] { return parallel_sum(v.begin(), v.end()); });
run(v, [&v] { return std::accumulate(v.begin(), v.end(), 0); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment