1 // Copyright 2017 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 "absl/strings/internal/char_map.h"
16 
17 #include <cstdint>
18 
19 #include "benchmark/benchmark.h"
20 
21 namespace {
22 
MakeBenchmarkMap()23 absl::strings_internal::Charmap MakeBenchmarkMap() {
24   absl::strings_internal::Charmap 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)
29       m = m | absl::strings_internal::Charmap::Char(i);
30   }
31   return m;
32 }
33 
34 // Micro-benchmark for Charmap::contains.
BM_Contains(benchmark::State & state)35 void BM_Contains(benchmark::State& state) {
36   // Loop-body replicated 10 times to increase time per iteration.
37   // Argument continuously changed to avoid generating common subexpressions.
38   const absl::strings_internal::Charmap 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   benchmark::DoNotOptimize(ops);
54 }
55 BENCHMARK(BM_Contains);
56 
57 // We don't bother benchmarking Charmap::IsZero or Charmap::IntersectsWith;
58 // their running time is data-dependent and it is not worth characterizing
59 // "typical" data.
60 
61 }  // namespace
62