-
Notifications
You must be signed in to change notification settings - Fork 0
/
virt_switch_bench.cpp
87 lines (73 loc) · 1.5 KB
/
virt_switch_bench.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <random>
struct Base {
virtual int GetN() = 0;
};
struct Foo1 : public Base {
int GetN() override {
return 1;
}
};
struct Foo2 : public Base {
int GetN() override {
return 2;
}
};
struct Foo3 : public Base {
int GetN() override {
return 3;
}
};
static void Virtual(benchmark::State& state) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(0,2);
std::array<Base*, 1000> arr;
for (size_t i = 0; i < arr.size(); i++) {
switch(dist6(rng)) {
case 0:
arr[i] = new Foo1;
break;
case 1:
arr[i] = new Foo2;
break;
case 2:
arr[i] = new Foo3;
break;
}
}
for (auto _ : state) {
for (size_t i = 0; i < arr.size(); i++) {
int res = arr[i]->GetN();
benchmark::DoNotOptimize(res);
}
}
}
BENCHMARK(Virtual);
struct TestSwitch {
int GetN(int n) {
switch(n) {
case 0:
return 1;
case 1:
return 2;
case 2:
return 3;
}
}
};
static void Switch(benchmark::State& state) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(0,2);
std::array<int, 1000> arr;
for (size_t i = 0; i < arr.size(); i++) {
arr[i] = dist6(rng);
}
for (auto _ : state) {
for (size_t i = 0; i < arr.size(); i++) {
int res = TestSwitch().GetN(arr[i]);
benchmark::DoNotOptimize(res);
}
}
}
BENCHMARK(Switch);