• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <unordered_set>
2 #include <vector>
3 #include <cstdint>
4 
5 #include "benchmark/benchmark_api.h"
6 #include "GenerateInput.hpp"
7 
8 constexpr std::size_t MAX_STRING_LEN = 8 << 14;
9 
10 // Benchmark when there is no match.
BM_StringFindNoMatch(benchmark::State & state)11 static void BM_StringFindNoMatch(benchmark::State &state) {
12   std::string s1(state.range(0), '-');
13   std::string s2(8, '*');
14   while (state.KeepRunning())
15     benchmark::DoNotOptimize(s1.find(s2));
16 }
17 BENCHMARK(BM_StringFindNoMatch)->Range(10, MAX_STRING_LEN);
18 
19 // Benchmark when the string matches first time.
BM_StringFindAllMatch(benchmark::State & state)20 static void BM_StringFindAllMatch(benchmark::State &state) {
21   std::string s1(MAX_STRING_LEN, '-');
22   std::string s2(state.range(0), '-');
23   while (state.KeepRunning())
24     benchmark::DoNotOptimize(s1.find(s2));
25 }
26 BENCHMARK(BM_StringFindAllMatch)->Range(1, MAX_STRING_LEN);
27 
28 // Benchmark when the string matches somewhere in the end.
BM_StringFindMatch1(benchmark::State & state)29 static void BM_StringFindMatch1(benchmark::State &state) {
30   std::string s1(MAX_STRING_LEN / 2, '*');
31   s1 += std::string(state.range(0), '-');
32   std::string s2(state.range(0), '-');
33   while (state.KeepRunning())
34     benchmark::DoNotOptimize(s1.find(s2));
35 }
36 BENCHMARK(BM_StringFindMatch1)->Range(1, MAX_STRING_LEN / 4);
37 
38 // Benchmark when the string matches somewhere from middle to the end.
BM_StringFindMatch2(benchmark::State & state)39 static void BM_StringFindMatch2(benchmark::State &state) {
40   std::string s1(MAX_STRING_LEN / 2, '*');
41   s1 += std::string(state.range(0), '-');
42   s1 += std::string(state.range(0), '*');
43   std::string s2(state.range(0), '-');
44   while (state.KeepRunning())
45     benchmark::DoNotOptimize(s1.find(s2));
46 }
47 BENCHMARK(BM_StringFindMatch2)->Range(1, MAX_STRING_LEN / 4);
48 
49 BENCHMARK_MAIN()
50