forked from apolukhin/course-nimble_cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mt_2.hpp
65 lines (50 loc) · 2.02 KB
/
mt_2.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
#include "util.hpp"
//////////////////////////// TASK 2 ////////////////////////////
struct naive_read_write_var_t {
std::atomic<int> variable{0};
int load() const {
return variable;
}
void store(int i) {
variable = i;
}
} naive_read_write_var;
struct optim_read_write_var_t {
std::atomic<int> variable{0};
int load() const {
return variable.load();
}
void store(int i) {
variable.store(i);
}
} optim_read_write_var;
//////////////////////////// DETAIL ////////////////////////////
enum class bench_t {
LOAD, STORE, LOAD_STORE
};
template <class Functor>
static void mt_load_store(benchmark::State& state, bench_t t, Functor& f) {
const std::size_t iterations_count = 8 << 10;
const auto do_stores = [&f,iterations_count](){
for (unsigned i = 0; i < iterations_count; ++i) {
f.store(i);
}
};
const auto do_loads = [&f,iterations_count](){
for (unsigned i = 0; i < iterations_count; ++i) {
const int val = f.load();
benchmark::DoNotOptimize(val);
}
};
switch (t) {
case bench_t::LOAD: for (auto _ : state) { do_loads(); do_loads(); do_loads(); do_loads(); }; break;
case bench_t::STORE:for (auto _ : state) { do_stores(); do_stores(); do_stores(); do_stores(); }; break;
default: for (auto _ : state) { do_loads(); do_loads(); do_loads(); do_stores(); }; break;
}
}
BENCH(mt_load_store, naive_LOAD, bench_t::LOAD, naive_read_write_var)->ThreadRange(1, 8);
BENCH(mt_load_store, optim_LOAD, bench_t::LOAD, optim_read_write_var)->ThreadRange(1, 8);
BENCH(mt_load_store, naive_STORE, bench_t::STORE, naive_read_write_var)->ThreadRange(1, 8);
BENCH(mt_load_store, optim_STORE, bench_t::STORE, optim_read_write_var)->ThreadRange(1, 8);
BENCH(mt_load_store, naive_MIXED, bench_t::LOAD_STORE, naive_read_write_var)->ThreadRange(1, 8);
BENCH(mt_load_store, optim_MIXED, bench_t::LOAD_STORE, optim_read_write_var)->ThreadRange(1, 8);