-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock_benchmark.cpp
60 lines (49 loc) · 1.2 KB
/
lock_benchmark.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <benchmark/benchmark.h>
#include <atomic>
uint32_t lock_underlying = 0;
class SpinLock {
std::atomic_flag locked = ATOMIC_FLAG_INIT ;
public:
void lock() {
while (locked.test_and_set(std::memory_order_acquire)) { ; }
}
void unlock() {
locked.clear(std::memory_order_release);
}
};
static SpinLock spinlock;
void lock(uint32_t* underlying) {
do {} while(not __sync_bool_compare_and_swap(underlying, 0, 1));
}
void unlock(uint32_t* underlying) {
do {} while(not __sync_bool_compare_and_swap(underlying, 1, 0));
}
void readModifyWrite(int* num) {
lock(&lock_underlying);
/*for (int i=0; i<1000; i++) {
*num = *num + 1;
}*/
unlock(&lock_underlying);
}
void readModifyWriteGccLock(int *num) {
spinlock.lock();
/*for (int i=0; i<1000; i++) {
*num = *num + 1;
}*/
spinlock.unlock();
}
static void BM_custom_lock(benchmark::State& state) {
int n = 0;
for (auto _ : state) {
readModifyWrite(&n);
}
}
static void BM_gcc_lock(benchmark::State& state) {
int n = 0;
for (auto _ : state) {
readModifyWriteGccLock(&n);
}
}
BENCHMARK(BM_custom_lock);
BENCHMARK(BM_gcc_lock);
BENCHMARK_MAIN();