Last active
July 24, 2024 06:04
-
-
Save virtuosonic/7b61f76242423ca76f6b380071a3039b to your computer and use it in GitHub Desktop.
how slow is a mutex lock
This file contains 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
/*************************************** | |
Author: Gabriel Espinoza | |
Desc: They say lock-based concurrency is slow | |
let's test how slow is slow | |
***************************************/ | |
#include <iostream> | |
#include <mutex> | |
#include <functional> | |
#include <chrono> | |
using namespace std; | |
using namespace std::chrono; | |
class C { | |
int x{}; | |
mutex m; | |
public: | |
void inc(){x++;} | |
void safe_inc(){ | |
lock_guard lk(m); | |
x++; | |
} | |
}c; | |
void run50000(function<void()> f) | |
{ | |
auto start = steady_clock::now(); | |
for( int i = 0; i < 50000; ++i) | |
{ | |
f(); | |
} | |
cout << "run time " << duration_cast<nanoseconds>(steady_clock::now() - start) << endl ; | |
} | |
int main() | |
{ | |
cout <<"running inc()\n"; | |
run50000(bind(&C::inc,&c)); | |
cout <<"running safe_inc()\n"; | |
run50000(bind(&C::safe_inc,&c)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment