Skip to content

Instantly share code, notes, and snippets.

@sehe
Created August 26, 2022 16:21
Show Gist options
  • Save sehe/a32a1dd8dfd99f85422f0a436d363dea to your computer and use it in GitHub Desktop.
Save sehe/a32a1dd8dfd99f85422f0a436d363dea to your computer and use it in GitHub Desktop.
tweaking a simple Asio channel benchmark
//#define TWEAKS
#ifdef TWEAKS
#define BOOST_ASIO_DISABLE_THREADS 1
#endif
#include <boost/asio.hpp>
#include <boost/asio/experimental/awaitable_operators.hpp>
#include <boost/asio/experimental/channel.hpp>
#include <iostream>
namespace asio = boost::asio;
using namespace asio::experimental::awaitable_operators;
using boost::system::error_code;
using context = asio::io_context;
#ifdef TWEAKS
using executor_t = context::executor_type;
using channel_t = asio::experimental::channel<executor_t, void(error_code, uint64_t)>;
#else
using executor_t = asio::any_io_executor;
using channel_t = asio::experimental::channel<void(error_code, uint64_t)>;
#endif
asio::awaitable<void> producer(channel_t& ch) {
for (uint64_t i = 0; i < 30'000; i++)
co_await ch.async_send(error_code {}, i, asio::use_awaitable);
ch.close();
}
asio::awaitable<void> consumer(channel_t& ch) {
for (;;)
co_await ch.async_receive(asio::use_awaitable);
}
asio::awaitable<void> experiment() {
asio::any_io_executor ex = co_await asio::this_coro::executor;
channel_t ch { *ex.target<executor_t>(), 1000 };
co_await (consumer(ch) && producer(ch));
}
void foo() {
try {
#ifdef TWEAKS
asio::io_context ctx{BOOST_ASIO_CONCURRENCY_HINT_UNSAFE};
#else
asio::io_context ctx{1};
#endif
asio::co_spawn(ctx, experiment(), asio::detached);
ctx.run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}
#include <nonius/benchmark.h++>
#define NONIUS_RUNNER
#include <nonius/main.h++>
NONIUS_BENCHMARK( //
"foo", //
[](nonius::chronometer cm) { cm.measure([] { foo(); }); })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment