1 #include "benchmark/benchmark.h"
2
3 #include <assert.h>
4 #include <math.h>
5 #include <stdint.h>
6
7 #include <chrono>
8 #include <complex>
9 #include <cstdlib>
10 #include <iostream>
11 #include <limits>
12 #include <list>
13 #include <map>
14 #include <mutex>
15 #include <set>
16 #include <sstream>
17 #include <string>
18 #include <thread>
19 #include <utility>
20 #include <vector>
21
22 #if defined(__GNUC__)
23 #define BENCHMARK_NOINLINE __attribute__((noinline))
24 #else
25 #define BENCHMARK_NOINLINE
26 #endif
27
28 namespace {
29
Factorial(int n)30 int BENCHMARK_NOINLINE Factorial(int n) {
31 return (n == 1) ? 1 : n * Factorial(n - 1);
32 }
33
CalculatePi(int depth)34 double CalculatePi(int depth) {
35 double pi = 0.0;
36 for (int i = 0; i < depth; ++i) {
37 double numerator = static_cast<double>(((i % 2) * 2) - 1);
38 double denominator = static_cast<double>((2 * i) - 1);
39 pi += numerator / denominator;
40 }
41 return (pi - 1.0) * 4;
42 }
43
ConstructRandomSet(int64_t size)44 std::set<int64_t> ConstructRandomSet(int64_t size) {
45 std::set<int64_t> s;
46 for (int i = 0; i < size; ++i) s.insert(s.end(), i);
47 return s;
48 }
49
50 std::mutex test_vector_mu;
51 std::vector<int>* test_vector = nullptr;
52
53 } // end namespace
54
BM_Factorial(benchmark::State & state)55 static void BM_Factorial(benchmark::State& state) {
56 int fac_42 = 0;
57 for (auto _ : state) fac_42 = Factorial(8);
58 // Prevent compiler optimizations
59 std::stringstream ss;
60 ss << fac_42;
61 state.SetLabel(ss.str());
62 }
63 BENCHMARK(BM_Factorial);
64 BENCHMARK(BM_Factorial)->UseRealTime();
65
BM_CalculatePiRange(benchmark::State & state)66 static void BM_CalculatePiRange(benchmark::State& state) {
67 double pi = 0.0;
68 for (auto _ : state) pi = CalculatePi(static_cast<int>(state.range(0)));
69 std::stringstream ss;
70 ss << pi;
71 state.SetLabel(ss.str());
72 }
73 BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);
74
BM_CalculatePi(benchmark::State & state)75 static void BM_CalculatePi(benchmark::State& state) {
76 static const int depth = 1024;
77 for (auto _ : state) {
78 double pi = CalculatePi(static_cast<int>(depth));
79 benchmark::DoNotOptimize(pi);
80 }
81 }
82 BENCHMARK(BM_CalculatePi)->Threads(8);
83 BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);
84 BENCHMARK(BM_CalculatePi)->ThreadPerCpu();
85
BM_SetInsert(benchmark::State & state)86 static void BM_SetInsert(benchmark::State& state) {
87 std::set<int64_t> data;
88 for (auto _ : state) {
89 state.PauseTiming();
90 data = ConstructRandomSet(state.range(0));
91 state.ResumeTiming();
92 for (int j = 0; j < state.range(1); ++j) data.insert(rand());
93 }
94 state.SetItemsProcessed(state.iterations() * state.range(1));
95 state.SetBytesProcessed(state.iterations() * state.range(1) *
96 static_cast<int64_t>(sizeof(int)));
97 }
98
99 // Test many inserts at once to reduce the total iterations needed. Otherwise,
100 // the slower, non-timed part of each iteration will make the benchmark take
101 // forever.
102 BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}});
103
104 template <typename Container,
105 typename ValueType = typename Container::value_type>
BM_Sequential(benchmark::State & state)106 static void BM_Sequential(benchmark::State& state) {
107 ValueType v = 42;
108 for (auto _ : state) {
109 Container c;
110 for (int64_t i = state.range(0); --i;) c.push_back(v);
111 }
112 const int64_t items_processed = state.iterations() * state.range(0);
113 state.SetItemsProcessed(items_processed);
114 state.SetBytesProcessed(items_processed * static_cast<int64_t>(sizeof(v)));
115 }
116 BENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int)
117 ->Range(1 << 0, 1 << 10);
118 BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10);
119 // Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond.
120 #ifdef BENCHMARK_HAS_CXX11
121 BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512);
122 #endif
123
BM_StringCompare(benchmark::State & state)124 static void BM_StringCompare(benchmark::State& state) {
125 size_t len = static_cast<size_t>(state.range(0));
126 std::string s1(len, '-');
127 std::string s2(len, '-');
128 for (auto _ : state) {
129 auto comp = s1.compare(s2);
130 benchmark::DoNotOptimize(comp);
131 }
132 }
133 BENCHMARK(BM_StringCompare)->Range(1, 1 << 20);
134
BM_SetupTeardown(benchmark::State & state)135 static void BM_SetupTeardown(benchmark::State& state) {
136 if (state.thread_index() == 0) {
137 // No need to lock test_vector_mu here as this is running single-threaded.
138 test_vector = new std::vector<int>();
139 }
140 int i = 0;
141 for (auto _ : state) {
142 std::lock_guard<std::mutex> l(test_vector_mu);
143 if (i % 2 == 0)
144 test_vector->push_back(i);
145 else
146 test_vector->pop_back();
147 ++i;
148 }
149 if (state.thread_index() == 0) {
150 delete test_vector;
151 }
152 }
153 BENCHMARK(BM_SetupTeardown)->ThreadPerCpu();
154
BM_LongTest(benchmark::State & state)155 static void BM_LongTest(benchmark::State& state) {
156 double tracker = 0.0;
157 for (auto _ : state) {
158 for (int i = 0; i < state.range(0); ++i)
159 benchmark::DoNotOptimize(tracker += i);
160 }
161 }
162 BENCHMARK(BM_LongTest)->Range(1 << 16, 1 << 28);
163
BM_ParallelMemset(benchmark::State & state)164 static void BM_ParallelMemset(benchmark::State& state) {
165 int64_t size = state.range(0) / static_cast<int64_t>(sizeof(int));
166 int thread_size = static_cast<int>(size) / state.threads();
167 int from = thread_size * state.thread_index();
168 int to = from + thread_size;
169
170 if (state.thread_index() == 0) {
171 test_vector = new std::vector<int>(static_cast<size_t>(size));
172 }
173
174 for (auto _ : state) {
175 for (int i = from; i < to; i++) {
176 // No need to lock test_vector_mu as ranges
177 // do not overlap between threads.
178 benchmark::DoNotOptimize(test_vector->at(static_cast<size_t>(i)) = 1);
179 }
180 }
181
182 if (state.thread_index() == 0) {
183 delete test_vector;
184 }
185 }
186 BENCHMARK(BM_ParallelMemset)->Arg(10 << 20)->ThreadRange(1, 4);
187
BM_ManualTiming(benchmark::State & state)188 static void BM_ManualTiming(benchmark::State& state) {
189 int64_t slept_for = 0;
190 int64_t microseconds = state.range(0);
191 std::chrono::duration<double, std::micro> sleep_duration{
192 static_cast<double>(microseconds)};
193
194 for (auto _ : state) {
195 auto start = std::chrono::high_resolution_clock::now();
196 // Simulate some useful workload with a sleep
197 std::this_thread::sleep_for(
198 std::chrono::duration_cast<std::chrono::nanoseconds>(sleep_duration));
199 auto end = std::chrono::high_resolution_clock::now();
200
201 auto elapsed =
202 std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
203
204 state.SetIterationTime(elapsed.count());
205 slept_for += microseconds;
206 }
207 state.SetItemsProcessed(slept_for);
208 }
209 BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseRealTime();
210 BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseManualTime();
211
212 #ifdef BENCHMARK_HAS_CXX11
213
214 template <class... Args>
BM_with_args(benchmark::State & state,Args &&...)215 void BM_with_args(benchmark::State& state, Args&&...) {
216 for (auto _ : state) {
217 }
218 }
219 BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44);
220 BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"),
221 std::pair<int, double>(42, 3.8));
222
BM_non_template_args(benchmark::State & state,int,double)223 void BM_non_template_args(benchmark::State& state, int, double) {
224 while (state.KeepRunning()) {
225 }
226 }
227 BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0);
228
229 #endif // BENCHMARK_HAS_CXX11
230
BM_DenseThreadRanges(benchmark::State & st)231 static void BM_DenseThreadRanges(benchmark::State& st) {
232 switch (st.range(0)) {
233 case 1:
234 assert(st.threads() == 1 || st.threads() == 2 || st.threads() == 3);
235 break;
236 case 2:
237 assert(st.threads() == 1 || st.threads() == 3 || st.threads() == 4);
238 break;
239 case 3:
240 assert(st.threads() == 5 || st.threads() == 8 || st.threads() == 11 ||
241 st.threads() == 14);
242 break;
243 default:
244 assert(false && "Invalid test case number");
245 }
246 while (st.KeepRunning()) {
247 }
248 }
249 BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3);
250 BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2);
251 BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3);
252
BM_BenchmarkName(benchmark::State & state)253 static void BM_BenchmarkName(benchmark::State& state) {
254 for (auto _ : state) {
255 }
256
257 // Check that the benchmark name is passed correctly to `state`.
258 assert("BM_BenchmarkName" == state.name());
259 }
260 BENCHMARK(BM_BenchmarkName);
261
262 // regression test for #1446
263 template <typename type>
BM_templated_test(benchmark::State & state)264 static void BM_templated_test(benchmark::State& state) {
265 for (auto _ : state) {
266 type created_string;
267 benchmark::DoNotOptimize(created_string);
268 }
269 }
270
271 static auto BM_templated_test_double = BM_templated_test<std::complex<double>>;
272 BENCHMARK(BM_templated_test_double);
273
274 BENCHMARK_MAIN();
275