Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Compile and run with:
// g++ -std=c++14 -O3 -Wall map_map_performance_test.cpp -o map_map_performance_test && ./map_map_performance_test
// ./map_map_performance_test
// Output on my machine:
// std::map<int, std::map<int, int>> --> elapsed_ms: 1471
// std::map<std::pair<int, int>, int> -> elapsed_ms: 2962
#include <chrono>
#include <iostream>
#include <map>
#include <random>
int main()
{
using namespace std::chrono;
const std::size_t runs = 3000000;
const auto start_time_ns = high_resolution_clock::now().time_since_epoch().count();
std::random_device rd;
std::uniform_int_distribution<int> dist(0, 100);
{
std::map<int, std::map<int, int>> map_map;
for (size_t i = 0; i < runs; ++i)
{
map_map[dist(rd)][dist(rd)] = dist(rd);
}
const auto end_time_ns = high_resolution_clock::now().time_since_epoch().count();
const auto elapsed_ms = (end_time_ns - start_time_ns) / 1000000;
std::cout << "std::map<int, std::map<int, int>> --> elapsed_ms: " << elapsed_ms << std::endl;
}
{
std::map<std::pair<int, int>, int> pair_map;
for (size_t i = 0; i < runs; ++i)
{
pair_map[std::make_pair(dist(rd), dist(rd))] = dist(rd);
}
const auto end_time_ns = high_resolution_clock::now().time_since_epoch().count();
const auto elapsed_ms = (end_time_ns - start_time_ns) / 1000000;
std::cout << "std::map<std::pair<int, int>, int> -> elapsed_ms: " << elapsed_ms << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment