xref: /aosp_15_r20/external/cronet/third_party/abseil-cpp/absl/strings/charset_benchmark.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2020 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 
17 #include "benchmark/benchmark.h"
18 #include "absl/log/check.h"
19 #include "absl/strings/charset.h"
20 
21 namespace {
22 
MakeBenchmarkMap()23 absl::CharSet MakeBenchmarkMap() {
24   absl::CharSet m;
25   uint32_t x[] = {0x0, 0x1, 0x2, 0x3, 0xf, 0xe, 0xd, 0xc};
26   for (uint32_t& t : x) t *= static_cast<uint32_t>(0x11111111UL);
27   for (uint32_t i = 0; i < 256; ++i) {
28     if ((x[i / 32] >> (i % 32)) & 1) m = m | absl::CharSet::Char(i);
29   }
30   return m;
31 }
32 
33 // Micro-benchmark for Charmap::contains.
BM_Contains(benchmark::State & state)34 static void BM_Contains(benchmark::State& state) {
35   // Loop-body replicated 10 times to increase time per iteration.
36   // Argument continuously changed to avoid generating common subexpressions.
37   // Final CHECK used to discourage unwanted optimization.
38   const absl::CharSet benchmark_map = MakeBenchmarkMap();
39   unsigned char c = 0;
40   int ops = 0;
41   for (auto _ : state) {
42     ops += benchmark_map.contains(c++);
43     ops += benchmark_map.contains(c++);
44     ops += benchmark_map.contains(c++);
45     ops += benchmark_map.contains(c++);
46     ops += benchmark_map.contains(c++);
47     ops += benchmark_map.contains(c++);
48     ops += benchmark_map.contains(c++);
49     ops += benchmark_map.contains(c++);
50     ops += benchmark_map.contains(c++);
51     ops += benchmark_map.contains(c++);
52   }
53   CHECK_NE(ops, -1);
54 }
55 BENCHMARK(BM_Contains);
56 
57 }  // namespace
58