1 #include "benchmark/benchmark.h"
2 
3 #include <cstdlib>
4 #include <map>
5 
6 namespace {
7 
ConstructRandomMap(int size)8 std::map<int, int> ConstructRandomMap(int size) {
9   std::map<int, int> m;
10   for (int i = 0; i < size; ++i) {
11     m.insert(std::make_pair(std::rand() % size, std::rand() % size));
12   }
13   return m;
14 }
15 
16 }  // namespace
17 
18 // Basic version.
BM_MapLookup(benchmark::State & state)19 static void BM_MapLookup(benchmark::State& state) {
20   const int size = static_cast<int>(state.range(0));
21   std::map<int, int> m;
22   for (auto _ : state) {
23     state.PauseTiming();
24     m = ConstructRandomMap(size);
25     state.ResumeTiming();
26     for (int i = 0; i < size; ++i) {
27       benchmark::DoNotOptimize(m.find(std::rand() % size));
28     }
29   }
30   state.SetItemsProcessed(state.iterations() * size);
31 }
32 BENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12);
33 
34 // Using fixtures.
35 class MapFixture : public ::benchmark::Fixture {
36  public:
SetUp(const::benchmark::State & st)37   void SetUp(const ::benchmark::State& st) {
38     m = ConstructRandomMap(static_cast<int>(st.range(0)));
39   }
40 
TearDown(const::benchmark::State &)41   void TearDown(const ::benchmark::State&) { m.clear(); }
42 
43   std::map<int, int> m;
44 };
45 
BENCHMARK_DEFINE_F(MapFixture,Lookup)46 BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) {
47   const int size = static_cast<int>(state.range(0));
48   for (auto _ : state) {
49     for (int i = 0; i < size; ++i) {
50       benchmark::DoNotOptimize(m.find(std::rand() % size));
51     }
52   }
53   state.SetItemsProcessed(state.iterations() * size);
54 }
55 BENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(1 << 3, 1 << 12);
56 
57 BENCHMARK_MAIN();
58