Last active
April 13, 2016 11:40
-
-
Save dongguosheng/8eb77bdd16a0ebed1e7ad6a3b5d06826 to your computer and use it in GitHub Desktop.
compare normal, c++11 thread and openmp
This file contains 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 <iostream> | |
#include <ctime> | |
#include <random> | |
#include <vector> | |
#include <thread> | |
#include <omp.h> | |
using namespace std; | |
const static int TOTAL_SIZE = 100000; | |
const static int THREAD_NUM = omp_get_max_threads(); | |
const static int RANGE = 100000; | |
const static int WALK_LEN = 40; | |
std::mt19937 rng(static_cast<int>(time(NULL))); | |
std::uniform_int_distribution<int> ud(0, RANGE); | |
inline vector<int> get_walk() { | |
vector<int> walk; | |
walk.reserve(WALK_LEN); | |
for (int j = 0; j < WALK_LEN; ++j) { | |
walk.push_back(ud(rng)); | |
} | |
return walk; | |
} | |
inline vector<vector<int> > foo() { | |
vector<vector<int> > rs(TOTAL_SIZE, vector<int>()); | |
for (int i = 0; i < TOTAL_SIZE; i++) { | |
rs[i] = get_walk(); | |
} | |
return rs; | |
} | |
void task(vector<vector<int> >::iterator begin, vector<vector<int> >::iterator end) { | |
for (auto iter = begin; iter != end; ++iter) { | |
vector<int> walk = get_walk(); | |
*iter = walk; | |
} | |
} | |
inline vector<vector<int> > foo_thread() { | |
vector<vector<int> > rs(TOTAL_SIZE, vector<int>()); | |
vector<thread> threads(THREAD_NUM); | |
int gap = TOTAL_SIZE / THREAD_NUM; | |
vector<vector<int> >::iterator iter = rs.begin(); | |
for (auto & t : threads) { | |
t = thread(task, iter, iter + gap > rs.end() ? rs.end() : iter + gap); | |
iter += gap; | |
} | |
for (auto & t : threads) { | |
t.join(); | |
} | |
return rs; | |
} | |
inline vector<vector<int> > foo_omp() { | |
vector<vector<int> > rs(TOTAL_SIZE, vector<int>()); | |
# pragma omp parallel for num_threads(THREAD_NUM) | |
for (int i = 0; i < TOTAL_SIZE; i++) { | |
rs[i] = get_walk(); | |
} | |
return rs; | |
} | |
int main() { | |
clock_t start = clock(); | |
vector<vector<int> > rs = foo(); | |
clock_t end = clock(); | |
cout << ((float)(end - start)) / CLOCKS_PER_SEC * 1000 << " ms." << endl; | |
cout << rs.size() << endl; | |
start = clock(); | |
rs = foo_thread(); | |
end = clock(); | |
cout << ((float)(end - start)) / CLOCKS_PER_SEC * 1000 << " ms." << endl; | |
cout << rs.size() << endl; | |
start = clock(); | |
rs = foo_omp(); | |
end = clock(); | |
cout << ((float)(end - start)) / CLOCKS_PER_SEC * 1000 << " ms." << endl; | |
cout << rs.size() << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
7031 ms
100000
2298 ms
100000
2381 ms
100000