Skip to content

Instantly share code, notes, and snippets.

@ipapadop
Last active October 24, 2016 12:50
Show Gist options
  • Save ipapadop/08722cf2033f018a273a1d7114164da7 to your computer and use it in GitHub Desktop.
Save ipapadop/08722cf2033f018a273a1d7114164da7 to your computer and use it in GitHub Desktop.
Comparing generating std::vector<int> against generator using Boost.Coroutine2.
// Tested under Boost 1.62
#include <iostream>
#include <chrono>
#include <vector>
#include <functional>
#include <boost/coroutine2/all.hpp>
#include <boost/lexical_cast.hpp>
std::vector<int> generateValues(unsigned int N, int start, int stride)
{
std::vector<int> v;
v.reserve(N);
for (; N > 0; --N, start += stride) {
v.push_back(start);
}
return v;
}
using coro_t = boost::coroutines2::coroutine<int>;
using generator = coro_t::pull_type;
using yield_type = coro_t::push_type;
void generateValuesImpl(yield_type& yield, unsigned int N, int start, int stride)
{
for (; N > 0; --N, start += stride) {
yield(start);
}
}
int main(int argc, char *argv[])
{
const unsigned int NEXPS = 100;
const unsigned int N = 10000000;
const int start = 10;
const int stride = 3;
int experiment = 0;
if (argc > 1) {
experiment = boost::lexical_cast<int>(argv[1]);
}
if (experiment==0 || experiment==1) {
int result = 0;
const auto start_time = std::chrono::system_clock::now();
for (auto i = NEXPS; i > 0; --i) {
const auto v = generateValues(N, start + i, stride);
for (auto&& t : v) {
result += t;
}
}
const std::chrono::duration<double> time =
std::chrono::system_clock::now() - start_time;
std::cout << "Traditional: " << result << ' ' << time.count() << " secs\n";
}
if (experiment==0 || experiment==2) {
int result = 0;
const auto start_time = std::chrono::system_clock::now();
for (auto i = NEXPS; i > 0; --i) {
#if 1
generator f{[&](yield_type& yield)
{
generateValuesImpl(yield, N, start + i, stride);
}}; // why no std::bind? does not compile
#else
// compiles with Boost.Coroutine but not with Boost.Coroutine2
generator f{std::bind(generateValuesImpl,
std::placeholders::_1, N, start + i, stride)};
#endif
for (auto&& t : f) {
result += t;
}
}
const std::chrono::duration<double> time =
std::chrono::system_clock::now() - start_time;
std::cout << "coroutine: " << result << ' ' << time.count() << " secs\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment