Skip to content

Instantly share code, notes, and snippets.

@Clemapfel
Created April 30, 2022 00:47
Show Gist options
  • Save Clemapfel/7e741ce78201e0dd10b17795229181d3 to your computer and use it in GitHub Desktop.
Save Clemapfel/7e741ce78201e0dd10b17795229181d3 to your computer and use it in GitHub Desktop.
#include <jluna.hpp>
#include <.benchmark/benchmark.hpp>
#include <.benchmark/benchmark_aux.hpp>
#include <thread>
#include <future>
#include <queue>
using namespace jluna;
int main()
{
// setup 1-thread threapool
static std::mutex queue_mutex;
static auto queue_lock = std::unique_lock(queue_mutex, std::defer_lock);
static std::condition_variable queue_cv;
static auto queue = std::queue<std::packaged_task<void()>>();
static auto shutdown = false;
static std::mutex master_mutex;
static auto master_lock = std::unique_lock(queue_mutex, std::defer_lock);
static std::condition_variable master_cv;
// worker thread
static auto thread = std::thread([](){
while (true)
{
queue_cv.wait(queue_lock, []() -> bool {
return not queue.empty() or shutdown;
});
if (shutdown)
return;
auto task = std::move(queue.front());
queue.pop();
task();
master_cv.notify_all();
}
});
// task
std::function<void()> task = []() {
size_t sum = 0;
for (volatile auto i = 0; i < 100; ++i)
sum += generate_number<Int64>();
return sum;
};
initialize(1);
size_t n_reps = 5000000;
// run task using jluna::Task
Benchmark::run_as_base("threading: jluna::Task", n_reps, [&]()
{
auto t = ThreadPool::create<void()>(task);
t.schedule();
t.join();
});
// run task using std::thread
Benchmark::run("threading: std::thread", n_reps, [&]()
{
queue.emplace(std::packaged_task<void()>(task));
queue_cv.notify_all();
master_cv.wait(master_lock, [](){
return queue.empty();
});
});
shutdown = true;
thread.detach();
queue_cv.notify_all();
Benchmark::conclude();
return 0;
}
/* Results:
[JULIA][LOG] initialization successful (1 thread(s)).
[C++][LOG] Running "threading: jluna::Task"
[C++][LOG] done.
[C++][LOG] Running "threading: std::thread"
[C++][LOG] done.
┌────────────────────────────────
│ threading: jluna::Task (5000001):
│ Min : 0.016554ms
│ Average: 0.019739ms
│ Max : 330.963ms
│ Median : 0.01833ms
│ Overhead: 0%
└────────────────────────────────
┌────────────────────────────────
│ threading: std::thread (5000001):
│ Min : 0.014566ms
│ Average: 0.018084ms
│ Max : 1.99318ms
│ Median : 0.017199ms
│ Overhead: -6.17021%
└────────────────────────────────
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment