Last active
July 18, 2016 13:01
-
-
Save mnowotnik/5f99d3216e7b3e4b3d8bcca2120aa12d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <omp.h> | |
#include <random> | |
#include <vector> | |
#include <iostream> | |
#include <chrono> | |
using namespace std; | |
using namespace std::chrono; | |
std::vector<int> transform(const std::vector<int> &v) { | |
std::vector<int> r; | |
for (auto i : v) { | |
if (i == 0) { | |
r.push_back(i); | |
} | |
} | |
return r; | |
} | |
std::vector<int> transform_mt(const std::vector<int> &v) { | |
std::vector<int> sizes(100); | |
#pragma omp parallel for schedule(static) shared(v, sizes) | |
for (unsigned i = 0; i < v.size(); i++) { | |
auto e = v[i]; | |
if (e == 0) { | |
sizes[omp_get_thread_num()] += 1; | |
} | |
} | |
int rsize = 0; | |
for (auto size : sizes) { | |
rsize += size; | |
} | |
std::vector<int> r(rsize); | |
unsigned j = 0; | |
#pragma omp parallel for schedule(static) shared(r, v, sizes) firstprivate(j) | |
for (unsigned i = 0; i < v.size(); i++) { | |
if (j == 0) { | |
j = omp_get_thread_num() > 0 ? sizes[omp_get_thread_num() - 1] : 0; | |
} | |
auto e = v[i]; | |
if (e == 0) { | |
r[j] = e; | |
j++; | |
} | |
} | |
return r; | |
} | |
int main() { | |
std::random_device rd; | |
std::mt19937_64 gen(rd()); | |
std::uniform_int_distribution<unsigned long long> dis; | |
const int vec_size = 1000000; | |
std::vector<int> v(vec_size); | |
for (int i = 0; i < vec_size; i++) { | |
v[i] = dis(gen) % 2; | |
} | |
high_resolution_clock::time_point t1 = high_resolution_clock::now(); | |
/* transform(v); */ | |
transform_mt(v); | |
high_resolution_clock::time_point t2 = high_resolution_clock::now(); | |
auto duration = duration_cast<microseconds>(t2 - t1).count(); | |
cout << "TIME: " << duration << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment