forked from taskflow/taskflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel_for.cpp
86 lines (71 loc) · 2.22 KB
/
parallel_for.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <taskflow/taskflow.hpp>
#include <cassert>
#include <numeric>
// Function: fib
int fib(int n) {
if(n <= 2) return n;
return (fib(n-1) + fib(n-2))%1024;
}
// ------------------------------------------------------------------------------------------------
// Procedure: sequential
void sequential(int N) {
auto tbeg = std::chrono::steady_clock::now();
for(int i=0; i<N; ++i) {
printf("fib[%d]=%d\n", i, fib(i));
}
auto tend = std::chrono::steady_clock::now();
std::cout << "sequential version takes "
<< std::chrono::duration_cast<std::chrono::milliseconds>(tend-tbeg).count()
<< " ms\n";
}
// Procedure: taskflow
void taskflow(int N) {
std::vector<int> range(N);
std::iota(range.begin(), range.end(), 0);
auto tbeg = std::chrono::steady_clock::now();
tf::Taskflow tf;
tf.parallel_for(range, [&] (const int i) {
printf("fib[%d]=%d\n", i, fib(i));
});
tf.wait_for_all();
auto tend = std::chrono::steady_clock::now();
std::cout << "taskflow version takes "
<< std::chrono::duration_cast<std::chrono::milliseconds>(tend-tbeg).count()
<< " ms\n";
}
// Procedure: openmp
void openmp(int N) {
std::vector<int> range(N);
std::iota(range.begin(), range.end(), 0);
auto tbeg = std::chrono::steady_clock::now();
#pragma omp parallel for
for(int i=0; i<N; ++i) {
printf("fib[%d]=%d\n", range[i], fib(range[i]));
}
auto tend = std::chrono::steady_clock::now();
std::cout << "openmp version takes "
<< std::chrono::duration_cast<std::chrono::milliseconds>(tend-tbeg).count()
<< " ms\n";
}
// ------------------------------------------------------------------------------------------------
// Function: main
int main(int argc, char* argv[]) {
if(argc != 3) {
std::cerr << "usage: ./parallel_for [baseline|openmp|taskflow] N\n";
std::exit(EXIT_FAILURE);
}
// Run methods
if(std::string_view method(argv[1]); method == "baseline") {
sequential(std::atoi(argv[2]));
}
else if(method == "openmp") {
openmp(std::atoi(argv[2]));
}
else if(method == "taskflow") {
taskflow(std::atoi(argv[2]));
}
else {
std::cerr << "wrong method, shoud be [baseline|openmp|taskflow]\n";
}
return 0;
}