Skip to content

Instantly share code, notes, and snippets.

@virtuosonic
Last active July 24, 2024 06:04
Show Gist options
  • Save virtuosonic/7b61f76242423ca76f6b380071a3039b to your computer and use it in GitHub Desktop.
Save virtuosonic/7b61f76242423ca76f6b380071a3039b to your computer and use it in GitHub Desktop.
how slow is a mutex lock
/***************************************
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