-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallel_for.cpp
59 lines (45 loc) · 1.29 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
//
// Created by blackgeorge on 7/1/19.
//
#include <iostream>
#include <chrono>
#include <thread>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include "random_data.h"
#include "foo.h"
class ApplyFoo {
std::vector<int>* const my_a;
public:
explicit ApplyFoo(std::vector<int>* a): my_a{a} {}
void operator()(const tbb::blocked_range<int>& r) const {
std::vector<int>* a = my_a;
for (int i = r.begin(); i != r.end(); ++i)
Foo((*a)[i]);
}
};
void SerialApplyFoo(std::vector<int>* a, int n)
{
for (auto i = 0; i < n; ++i)
Foo((*a)[i]);
}
void ParallelApplyFoo(std::vector<int>* a, int n)
{
tbb::parallel_for(tbb::blocked_range<int>(0, n), ApplyFoo(a), tbb::auto_partitioner());
}
int main()
{
using namespace std::chrono;
int N = 100000000;
auto a = create_random_data(N);
auto t0 = high_resolution_clock::now();
SerialApplyFoo(&a, N);
auto tf = high_resolution_clock::now();
std::cout << "done " << duration_cast<milliseconds>(tf-t0).count() << " ms" << std::endl;
t0 = high_resolution_clock::now();
ParallelApplyFoo(&a, N);
tf = high_resolution_clock::now();
std::cout << "done " << duration_cast<milliseconds>(tf-t0).count() << " ms\n";
return 0;
}