forked from apolukhin/course-nimble_cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mt_1.hpp
89 lines (70 loc) · 2.22 KB
/
mt_1.hpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "util.hpp"
//////////////////////////// TASK 1 ////////////////////////////
struct naive_shared_var_t { // Do not modify!
std::mutex m;
int variable{0};
int inc() {
std::lock_guard<std::mutex> l{m};
return ++variable;
}
int dec() {
std::lock_guard<std::mutex> l{m};
return --variable;
}
} naive_shared_var;
struct wrong_shared_var_t { // Do not modify!
int variable{0};
int inc() {
return ++variable;
}
int dec() {
return --variable;
}
} wrong_shared_var;
struct super_shared_var_t {
std::mutex m;
int variable{0};
int inc() {
std::lock_guard<std::mutex> l{m};
return ++variable;
}
int dec() {
std::lock_guard<std::mutex> l{m};
return --variable;
}
} super_shared_var;
struct ultim_shared_var_t {
std::mutex m;
int variable{0};
int inc() {
std::lock_guard<std::mutex> l{m};
return ++variable;
}
int dec() {
std::lock_guard<std::mutex> l{m};
return --variable;
}
} ultim_shared_var;
//////////////////////////// DETAIL ////////////////////////////
template <class Functor>
static void mt_inc_dec(benchmark::State& state, Functor& f) {
const std::size_t iterations_count = state.range();
const auto func = [&f, iterations_count]() {
for (unsigned i = 0; i < iterations_count / 2; ++i) {
const int var = f.inc();
benchmark::DoNotOptimize(var);
}
for (unsigned i = 0; i < iterations_count / 2; ++i) {
const int var = f.dec();
benchmark::DoNotOptimize(var);
}
};
for (auto _ : state) {
func();
}
// std::cerr << "variable == " << f.variable << '\n';
}
BENCH(mt_inc_dec, naive_shared_var, naive_shared_var)->Unit(benchmark::kMicrosecond)->Arg(8 << 10)->ThreadRange(1, 8);
BENCH(mt_inc_dec, wrong_shared_var, wrong_shared_var)->Unit(benchmark::kMicrosecond)->Arg(8 << 10)->ThreadRange(1, 8);
BENCH(mt_inc_dec, super_shared_var, super_shared_var)->Unit(benchmark::kMicrosecond)->Arg(8 << 10)->ThreadRange(1, 8);
BENCH(mt_inc_dec, ultim_shared_var, ultim_shared_var)->Unit(benchmark::kMicrosecond)->Arg(8 << 10)->ThreadRange(1, 8);