Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <chrono>
#include <atomic>
#include <cassert>
#include <mutex>
const int ITERATIONS = 10'000'000;
std::mutex mtx;
int state = 2;
std::atomic<int> atomic_state{2};
void do_something();
void mutex_bench() {
for (int i=0; i<ITERATIONS; i++) {
{
std::lock_guard<std::mutex> guard(mtx);
assert(state == 2);
state = 1;
}
do_something();
{
std::lock_guard<std::mutex> guard(mtx);
assert(state == 1);
state = 2;
}
}
}
void atomic_bench() {
for (int i=0; i<ITERATIONS; i++) {
{
int expected = 2;
atomic_state.compare_exchange_weak(expected, 1, std::memory_order_relaxed, std::memory_order_relaxed);
assert(expected == 2);
}
do_something();
{
int expected = 1;
atomic_state.compare_exchange_weak(expected, 2, std::memory_order_relaxed, std::memory_order_relaxed);
assert(expected == 1);
}
}
}
int main() {
auto start = std::chrono::steady_clock::now();
mutex_bench();
auto middle = std::chrono::steady_clock::now();
atomic_bench();
auto end = std::chrono::steady_clock::now();
std::cout << "mutex: " << std::chrono::duration_cast<std::chrono::milliseconds>(middle - start).count() << "[ms]" << std::endl;
std::cout << "atomic: " << std::chrono::duration_cast<std::chrono::milliseconds> (end - middle).count() << "[ms]" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment