1 | #include <cstdlib> |
---|---|
2 | #include <map> |
3 | |
4 | #include "benchmark/benchmark.h" |
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(x: std::make_pair(x: std::rand() % size, y: std::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 = static_cast<int>(state.range(pos: 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 | auto it = m.find(x: std::rand() % size); |
28 | benchmark::DoNotOptimize(value&: it); |
29 | } |
30 | } |
31 | state.SetItemsProcessed(state.iterations() * size); |
32 | } |
33 | BENCHMARK(BM_MapLookup)->Range(start: 1 << 3, limit: 1 << 12); |
34 | |
35 | // Using fixtures. |
36 | class MapFixture : public ::benchmark::Fixture { |
37 | public: |
38 | void SetUp(const ::benchmark::State& st) override { |
39 | m = ConstructRandomMap(size: static_cast<int>(st.range(pos: 0))); |
40 | } |
41 | |
42 | void TearDown(const ::benchmark::State&) override { m.clear(); } |
43 | |
44 | std::map<int, int> m; |
45 | }; |
46 | |
47 | BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) { |
48 | const int size = static_cast<int>(state.range(pos: 0)); |
49 | for (auto _ : state) { |
50 | for (int i = 0; i < size; ++i) { |
51 | auto it = m.find(x: std::rand() % size); |
52 | benchmark::DoNotOptimize(value&: it); |
53 | } |
54 | } |
55 | state.SetItemsProcessed(state.iterations() * size); |
56 | } |
57 | BENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(start: 1 << 3, limit: 1 << 12); |
58 | |
59 | BENCHMARK_MAIN(); |
60 |