Skip to content

Instantly share code, notes, and snippets.

@lozhnikov
Last active March 31, 2020 10:00
Show Gist options
  • Save lozhnikov/3486432717ea04f25a722c97fbd79edd to your computer and use it in GitHub Desktop.
Save lozhnikov/3486432717ea04f25a722c97fbd79edd to your computer and use it in GitHub Desktop.
The test indicates that there's no sense in parallelizing simple loops over large datasets
#include <iostream>
#include <iomanip>
#include <random>
#include <chrono>
using namespace std;
using namespace chrono;
vector<pair<size_t, double>> TestParallel(const vector<size_t>& sizes) {
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(10, 100);
vector<pair<size_t, double>> result;
for (size_t size : sizes) {
std::vector<double> lhs;
std::vector<double> rhs;
lhs.reserve(size);
rhs.reserve(size);
for (size_t i = 0; i < size; i++) {
lhs.push_back(dis(gen));
rhs.push_back(dis(gen));
}
size_t count = 0;
auto start = steady_clock::now();
#pragma opm parallel for shared(count, lhs, rhs) reduce(+: count)
for (size_t i = 0; i < size; i++)
count += lhs[i] < rhs[i];
auto finish = steady_clock::now();
double duration = duration_cast<nanoseconds>(finish - start).count() * 1e-9;
result.push_back(make_pair(count, duration));
}
return result;
}
vector<pair<size_t, double>> TestSequential(const vector<size_t>& sizes) {
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(10, 100);
vector<pair<size_t, double>> result;
for (size_t size : sizes) {
std::vector<double> lhs;
std::vector<double> rhs;
lhs.reserve(size);
rhs.reserve(size);
for (size_t i = 0; i < size; i++) {
lhs.push_back(dis(gen));
rhs.push_back(dis(gen));
}
size_t count = 0;
auto start = steady_clock::now();
for (size_t i = 0; i < size; i++)
count += lhs[i] < rhs[i];
auto finish = steady_clock::now();
double duration = duration_cast<nanoseconds>(finish - start).count() * 1e-9;
result.push_back(make_pair(count, duration));
}
return result;
}
int main() {
vector<size_t> sizes = {
10, 100, 1'000, 10'000, 100'000, 1'000'000,
10'000'000, 100'000'000
};
vector<pair<size_t, double>> parallel = TestParallel(sizes);
vector<pair<size_t, double>> sequential = TestSequential(sizes);
cout << scientific;
cout << setw(12) << "Size" << " "
<< setw(12) << "Count Par." << " " << setw(12) << "Parallel (s)" << " "
<< setw(12) << "Count Seq." << " " << setw(12) << "Sequential (s)"
<< "\n";
for (size_t i = 0; i < sizes.size(); i++) {
cout << setw(12) << sizes[i] << " "
<< setw(12) << parallel[i].first << " " << parallel[i].second << " "
<< setw(12) << sequential[i].first << " " << sequential[i].second
<< "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment