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