Skip to content

Commit cae8296

Browse files
committed
Add has_single_bit benchmark
1 parent 59a62b8 commit cae8296

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

benchmarks/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ add_benchmark(efficient_nonlocking_print src/efficient_nonlocking_print.cpp)
114114
add_benchmark(filesystem src/filesystem.cpp)
115115
add_benchmark(find_and_count src/find_and_count.cpp)
116116
add_benchmark(find_first_of src/find_first_of.cpp)
117+
add_benchmark(has_single_bit src/has_single_bit.cpp)
117118
add_benchmark(iota src/iota.cpp)
118119
add_benchmark(locale_classic src/locale_classic.cpp)
119120
add_benchmark(minmax_element src/minmax_element.cpp)

benchmarks/src/has_single_bit.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3+
4+
#include <assert.h>
5+
#include <benchmark/benchmark.h>
6+
#include <bit>
7+
8+
#include <utility.hpp>
9+
10+
template <typename T>
11+
static void has_single_bit_if(benchmark::State& state) {
12+
const auto random_v = random_vector<T>(8);
13+
for (auto _ : state) {
14+
benchmark::DoNotOptimize(random_v);
15+
int count_true = 0, count_false = 0;
16+
for (const auto& x : random_v) {
17+
if (std::has_single_bit(x)) {
18+
benchmark::DoNotOptimize(count_true++);
19+
} else {
20+
benchmark::DoNotOptimize(count_false++);
21+
}
22+
}
23+
}
24+
}
25+
26+
template <typename T>
27+
static void has_single_bit(benchmark::State& state) {
28+
const auto random_v = random_vector<T>(8);
29+
assert(random_v.size() % 4 == 0);
30+
for (auto _ : state) {
31+
benchmark::DoNotOptimize(random_v);
32+
int r = 0, count_false = 0;
33+
for (size_t i = 0; i < random_v.size(); i += 4) {
34+
r += std::has_single_bit(random_v[i + 0]);
35+
r += std::has_single_bit(random_v[i + 1]);
36+
r += std::has_single_bit(random_v[i + 2]);
37+
r += std::has_single_bit(random_v[i + 3]);
38+
}
39+
benchmark::DoNotOptimize(r);
40+
}
41+
}
42+
43+
BENCHMARK(has_single_bit_if<uint16_t>);
44+
BENCHMARK(has_single_bit_if<uint32_t>);
45+
BENCHMARK(has_single_bit_if<uint64_t>);
46+
47+
BENCHMARK(has_single_bit<uint16_t>);
48+
BENCHMARK(has_single_bit<uint32_t>);
49+
BENCHMARK(has_single_bit<uint64_t>);
50+
51+
BENCHMARK_MAIN();

0 commit comments

Comments
 (0)