Skip to content

Instantly share code, notes, and snippets.

@OperationDarkside
Created September 25, 2018 23:11
Show Gist options
  • Save OperationDarkside/59c86f259fdefb863a805f49d96b3c3c to your computer and use it in GitHub Desktop.
Save OperationDarkside/59c86f259fdefb863a805f49d96b3c3c to your computer and use it in GitHub Desktop.
C++ Vector Index Performance
#include <iostream>
#include <tuple>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <chrono>
int main() {
std::unordered_map<int, int> index;
index.reserve (10000);
std::vector<std::tuple<int, int>> lin_index;
lin_index.resize (10000);
std::vector<big_ass_struct> to_search_vec;
to_search_vec.resize (10000);
// Set IDs
for (int i = 0; i < to_search_vec.size (); ++i) {
to_search_vec[i].id = i;
}
// Randomize
std::random_shuffle (to_search_vec.begin (), to_search_vec.end ());
// Create Index
for (int i = 0; i < to_search_vec.size (); ++i) {
index[to_search_vec[i].id] = i;
lin_index.push_back (std::make_tuple(to_search_vec[i].id, i));
}
// Create IDs to search for
std::vector<int> id_s;
id_s.resize (1000);
std::vector<int> found_id_s;
found_id_s.resize (1000);
for (int i = 0; i < id_s.size (); ++i) {
id_s[i] = i;
}
std::random_shuffle (id_s.begin (), id_s.end ());
// Without index
auto start_1 = std::chrono::high_resolution_clock::now ();
for (int id : id_s) {
for (auto& ele : to_search_vec) {
if (ele.id == id) {
found_id_s.push_back (ele.id);
}
}
}
auto end_1 = std::chrono::high_resolution_clock::now ();
auto dur_1 = end_1 - start_1;
std::cout << dur_1.count () << "\r\n";
// Cleanup
found_id_s.clear ();
// With Index
auto start_2 = std::chrono::high_resolution_clock::now ();
for (int id : id_s) {
int pos = index[id];
auto& ele = to_search_vec[pos];
found_id_s.push_back (ele.id);
}
auto end_2 = std::chrono::high_resolution_clock::now ();
auto dur_2 = end_2 - start_2;
std::cout << dur_2.count () << "\r\n";
// With linear Index
auto start_3 = std::chrono::high_resolution_clock::now ();
for (int id : id_s) {
for (auto& ind : lin_index) {
int index_id = std::get<0> (ind);
if (index_id == id) {
int index_index = std::get<1> (ind);
found_id_s.push_back (to_search_vec[index_index].id);
}
}
}
auto end_3 = std::chrono::high_resolution_clock::now ();
auto dur_3 = end_3 - start_3;
std::cout << dur_3.count () << "\r\n";
int bla;
std::cin >> bla;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment