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