xref: /aosp_15_r20/external/perfetto/src/base/flat_set_benchmark.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 // Copyright (C) 2019 The Android Open Source Project
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 //      http://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 <random>
16 #include <set>
17 #include <unordered_set>
18 
19 #include <benchmark/benchmark.h>
20 
21 #include "perfetto/base/flat_set.h"
22 
23 namespace {
24 
GetRandData(int num_pids)25 std::vector<int> GetRandData(int num_pids) {
26   std::vector<int> rnd_data;
27   std::minstd_rand0 rng(0);
28   static constexpr int kDistinctValues = 100;
29   for (int i = 0; i < num_pids; i++)
30     rnd_data.push_back(static_cast<int>(rng()) % kDistinctValues);
31   return rnd_data;
32 }
33 
IsBenchmarkFunctionalOnly()34 bool IsBenchmarkFunctionalOnly() {
35   return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
36 }
37 
BenchmarkArgs(benchmark::internal::Benchmark * b)38 void BenchmarkArgs(benchmark::internal::Benchmark* b) {
39   if (IsBenchmarkFunctionalOnly()) {
40     b->Arg(64);
41   } else {
42     b->RangeMultiplier(2)->Range(64, 4096);
43   }
44 }
45 
46 }  // namespace
47 
48 template <typename SetType>
BM_SetInsert(benchmark::State & state)49 static void BM_SetInsert(benchmark::State& state) {
50   std::vector<int> rnd_data = GetRandData(static_cast<int>(state.range(0)));
51   for (auto _ : state) {
52     SetType iset;
53     for (const int val : rnd_data)
54       iset.insert(val);
55     benchmark::DoNotOptimize(iset);
56     benchmark::DoNotOptimize(iset.begin());
57     benchmark::ClobberMemory();
58   }
59 }
60 
61 using perfetto::base::FlatSet;
62 BENCHMARK_TEMPLATE(BM_SetInsert, FlatSet<int>)->Apply(BenchmarkArgs);
63 BENCHMARK_TEMPLATE(BM_SetInsert, std::set<int>)->Apply(BenchmarkArgs);
64 BENCHMARK_TEMPLATE(BM_SetInsert, std::unordered_set<int>)->Apply(BenchmarkArgs);
65