Skip to content

Commit e95e6bc

Browse files
committed
fix: dont optimize out benches
1 parent 719c41f commit e95e6bc

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

examples/google_benchmark_cmake/main.cpp

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
template <class... Args>
99
void BM_Capture(benchmark::State &state, Args &&...args) {
1010
auto args_tuple = std::make_tuple(std::move(args)...);
11-
(void)args_tuple;
1211
for (auto _ : state) {
12+
benchmark::DoNotOptimize(args_tuple);
13+
benchmark::ClobberMemory();
1314
}
1415
}
1516
BENCHMARK_CAPTURE(BM_Capture, int_string_test, 42, std::string("abc"));
@@ -20,6 +21,8 @@ static void BM_rand_vector(benchmark::State &state) {
2021
std::vector<int> v;
2122
for (auto _ : state) {
2223
std::string empty_string;
24+
benchmark::DoNotOptimize(empty_string);
25+
benchmark::ClobberMemory();
2326
}
2427
}
2528
// Register the function as a benchmark
@@ -30,6 +33,8 @@ static void BM_StringCopy(benchmark::State &state) {
3033
std::string x = "hello";
3134
for (auto _ : state) {
3235
std::string copy(x);
36+
benchmark::DoNotOptimize(copy);
37+
benchmark::ClobberMemory();
3338
}
3439
}
3540
// Register the function as a benchmark
@@ -39,7 +44,11 @@ static void BM_memcpy(benchmark::State &state) {
3944
char *src = new char[state.range(0)];
4045
char *dst = new char[state.range(0)];
4146
memset(src, 'x', state.range(0));
42-
for (auto _ : state) memcpy(dst, src, state.range(0));
47+
for (auto _ : state) {
48+
memcpy(dst, src, state.range(0));
49+
benchmark::DoNotOptimize(dst);
50+
benchmark::ClobberMemory();
51+
}
4352
delete[] src;
4453
delete[] dst;
4554
}

examples/google_benchmark_cmake/template_bench.hpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ template <class T> void BM_Template(benchmark::State &state) {
1010
std::vector<T> v;
1111
for (auto _ : state) {
1212
v.push_back(T());
13+
benchmark::DoNotOptimize(v);
14+
benchmark::ClobberMemory();
1315
}
1416
}
1517
BENCHMARK_TEMPLATE(BM_Template, int);
@@ -46,6 +48,8 @@ template <typename T, class... ExtraArgs>
4648
void BM_Template1_Capture(benchmark::State &state, ExtraArgs &&...extra_args) {
4749
auto args_tuple = std::make_tuple(std::move(extra_args)...);
4850
for (auto _ : state) {
51+
benchmark::DoNotOptimize(args_tuple);
52+
benchmark::ClobberMemory();
4953
}
5054
}
5155
BENCHMARK_TEMPLATE1_CAPTURE(BM_Template1_Capture, void, int_string_test, 42,

0 commit comments

Comments
 (0)