Created
February 16, 2021 08:09
-
-
Save dinfuehr/cbe7f18ab93a59312a3b613bb3a5c4e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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