-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsynchronization.cpp
71 lines (59 loc) · 1.85 KB
/
synchronization.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
61
62
63
64
65
66
67
68
69
70
71
#include <benchmark/benchmark.h>
#include <mutex>
#include <atomic>
static void BM_noLockAdd(benchmark::State& state) {
long add = 0;
int N = 1024;
for (auto _ : state) {
for (int i = 0; i < N; ++i) {
benchmark::DoNotOptimize(add++);
}
}
benchmark::ClobberMemory();
}
volatile long mutex_add = 0;
std::mutex mutex_lock;
static void BM_MultiThreadedMutexAdd(benchmark::State& state) {
if (state.thread_index == 0) {
mutex_add = 0;
}
int N = 1024;
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
std::lock_guard<std::mutex> guard(mutex_lock);
mutex_add += 1;
benchmark::DoNotOptimize(mutex_add);
}
}
benchmark::ClobberMemory();
}
std::atomic_long atomic_add = 0;
static void BM_MultiThreadedAtomicAdd(benchmark::State& state) {
if (state.thread_index == 0) {
atomic_add = 0;
}
int N = 1024;
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
benchmark::DoNotOptimize(atomic_add++);
}
}
benchmark::ClobberMemory();
}
#define ARGS(N) ->Threads(N)->UseRealTime();
// Register the function as a benchmark
BENCHMARK(BM_noLockAdd);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(1);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(2);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(4);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(8);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(12);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(16);
BENCHMARK(BM_MultiThreadedMutexAdd) ARGS(32);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(1);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(2);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(4);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(8);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(12);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(16);
BENCHMARK(BM_MultiThreadedAtomicAdd) ARGS(32);