char_map_benchmark.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #include "absl/strings/internal/char_map.h"
  15. #include <cstdint>
  16. #include "benchmark/benchmark.h"
  17. namespace {
  18. absl::strings_internal::Charmap MakeBenchmarkMap() {
  19. absl::strings_internal::Charmap m;
  20. uint32_t x[] = {0x0, 0x1, 0x2, 0x3, 0xf, 0xe, 0xd, 0xc};
  21. for (uint32_t& t : x) t *= static_cast<uint32_t>(0x11111111UL);
  22. for (uint32_t i = 0; i < 256; ++i) {
  23. if ((x[i / 32] >> (i % 32)) & 1)
  24. m = m | absl::strings_internal::Charmap::Char(i);
  25. }
  26. return m;
  27. }
  28. // Micro-benchmark for Charmap::contains.
  29. void BM_Contains(benchmark::State& state) {
  30. // Loop-body replicated 10 times to increase time per iteration.
  31. // Argument continuously changed to avoid generating common subexpressions.
  32. const absl::strings_internal::Charmap benchmark_map = MakeBenchmarkMap();
  33. unsigned char c = 0;
  34. int ops = 0;
  35. for (auto _ : state) {
  36. ops += benchmark_map.contains(c++);
  37. ops += benchmark_map.contains(c++);
  38. ops += benchmark_map.contains(c++);
  39. ops += benchmark_map.contains(c++);
  40. ops += benchmark_map.contains(c++);
  41. ops += benchmark_map.contains(c++);
  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. }
  47. benchmark::DoNotOptimize(ops);
  48. }
  49. BENCHMARK(BM_Contains);
  50. // We don't bother benchmarking Charmap::IsZero or Charmap::IntersectsWith;
  51. // their running time is data-dependent and it is not worth characterizing
  52. // "typical" data.
  53. } // namespace