bits_benchmark.cc (2444B)
1 // Copyright 2022 The Abseil Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #include <cstdint> 16 #include <vector> 17 18 #include "absl/base/optimization.h" 19 #include "absl/numeric/bits.h" 20 #include "absl/random/random.h" 21 #include "benchmark/benchmark.h" 22 23 namespace absl { 24 namespace { 25 26 template <typename T> 27 static void BM_bit_width(benchmark::State& state) { 28 const auto count = static_cast<size_t>(state.range(0)); 29 30 absl::BitGen rng; 31 std::vector<T> values; 32 values.reserve(count); 33 for (size_t i = 0; i < count; ++i) { 34 values.push_back(absl::Uniform<T>(rng, 0, std::numeric_limits<T>::max())); 35 } 36 37 while (state.KeepRunningBatch(static_cast<int64_t>(count))) { 38 for (size_t i = 0; i < count; ++i) { 39 benchmark::DoNotOptimize(absl::bit_width(values[i])); 40 } 41 } 42 } 43 BENCHMARK_TEMPLATE(BM_bit_width, uint8_t)->Range(1, 1 << 20); 44 BENCHMARK_TEMPLATE(BM_bit_width, uint16_t)->Range(1, 1 << 20); 45 BENCHMARK_TEMPLATE(BM_bit_width, uint32_t)->Range(1, 1 << 20); 46 BENCHMARK_TEMPLATE(BM_bit_width, uint64_t)->Range(1, 1 << 20); 47 48 template <typename T> 49 static void BM_bit_width_nonzero(benchmark::State& state) { 50 const auto count = static_cast<size_t>(state.range(0)); 51 52 absl::BitGen rng; 53 std::vector<T> values; 54 values.reserve(count); 55 for (size_t i = 0; i < count; ++i) { 56 values.push_back(absl::Uniform<T>(rng, 1, std::numeric_limits<T>::max())); 57 } 58 59 while (state.KeepRunningBatch(static_cast<int64_t>(count))) { 60 for (size_t i = 0; i < count; ++i) { 61 const T value = values[i]; 62 ABSL_ASSUME(value > 0); 63 benchmark::DoNotOptimize(absl::bit_width(value)); 64 } 65 } 66 } 67 BENCHMARK_TEMPLATE(BM_bit_width_nonzero, uint8_t)->Range(1, 1 << 20); 68 BENCHMARK_TEMPLATE(BM_bit_width_nonzero, uint16_t)->Range(1, 1 << 20); 69 BENCHMARK_TEMPLATE(BM_bit_width_nonzero, uint32_t)->Range(1, 1 << 20); 70 BENCHMARK_TEMPLATE(BM_bit_width_nonzero, uint64_t)->Range(1, 1 << 20); 71 72 } // namespace 73 } // namespace absl