Skip to content

Instantly share code, notes, and snippets.

@HamedMasafi
Created May 22, 2022 06:52
Show Gist options
  • Save HamedMasafi/9d54d1894e633a96dcdd8959a26b8b68 to your computer and use it in GitHub Desktop.
Save HamedMasafi/9d54d1894e633a96dcdd8959a26b8b68 to your computer and use it in GitHub Desktop.
#include <random>
#include <iostream>
#include <set>
#include <chrono>
#include <iomanip>
constexpr int sum = 70;
constexpr int size = 1000;
void cout(const ulong &u1, const ulong &u2)
{
(void)u1;
(void)u2;
}
void test_basic(const std::vector<ulong> &vec) {
for(auto i = 0; i < size; i++)
for(auto j = 0; j < size; j++)
if (vec.at(i) + vec.at(j) == sum)
cout(vec.at(i), vec.at(j));
}
void test_set(const std::vector<ulong> &vec) {
std::set<ulong> set;
for(auto i = 0; i < size; i++) {
auto p = set.find(sum - vec.at(i));
if (p != set.end())
cout(vec.at(i), *p);
set.emplace(vec.at(i));
}
}
void run_test()
{
std::vector<unsigned long> vec;
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(1,100);
for(auto i = 0; i < size; i++)
vec.push_back(dist(rng));
auto start_basic = std::chrono::high_resolution_clock::now();
test_basic(vec);
auto end_basic = std::chrono::high_resolution_clock::now();
auto start_set = std::chrono::high_resolution_clock::now();
test_set(vec);
auto end_set = std::chrono::high_resolution_clock::now();
double elapsed_time_basic = std::chrono::duration<double, std::milli>(end_basic - start_basic).count();
double elapsed_time_set = std::chrono::duration<double, std::milli>(end_set - start_set).count();
std::cout << std::fixed << std::setprecision(6)
<< "Basic=" << std::showbase<<std::setw(10) << elapsed_time_basic
<< std::setw(6)
<< "Set=" << std::setw(10) << elapsed_time_set << std::endl;
}
int main(int, char *[])
{
for (auto i = 0; i < 20; i++)
run_test();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment