-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathhistogram_06_3rd_safe_parallel.cpp
More file actions
69 lines (58 loc) · 2.29 KB
/
Copy pathhistogram_06_3rd_safe_parallel.cpp
File metadata and controls
69 lines (58 loc) · 2.29 KB
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
/*
Copyright (c) 2025 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
#include <atomic>
#include <tbb/tick_count.h>
#include <tbb/parallel_for.h>
int main(int argc, char** argv) {
long int n = 1000000000;
constexpr int num_bins = 256;
// Initialize random number generator
std::random_device seed; // Random device seed
std::mt19937 mte{seed()}; // mersenne_twister_engine
std::uniform_int_distribution<> uniform{0,num_bins};
// Initialize image
std::vector<uint8_t> image; // empty vector
image.reserve(n); // image vector prealocated
std::generate_n(std::back_inserter(image), n,
[&] { return uniform(mte); }
);
// Initialize histogram
std::vector<int> hist(num_bins);
// Serial execution
tbb::tick_count t0 = tbb::tick_count::now();
std::for_each(image.begin(), image.end(),
[&](uint8_t i){hist[i]++;});
tbb::tick_count t1 = tbb::tick_count::now();
double t_serial = (t1 - t0).seconds();
// Parallel execution
std::vector<std::atomic<int>> hist_p(num_bins);
t0 = tbb::tick_count::now();
parallel_for(tbb::blocked_range<size_t>{0, image.size()},
[&](const tbb::blocked_range<size_t>& r)
{
for (size_t i = r.begin(); i < r.end(); ++i)
hist_p[image[i]]++;
});
t1 = tbb::tick_count::now();
double t_parallel = (t1 - t0).seconds();
std::cout << "Serial: " << t_serial << ", ";
std::cout << "Parallel: " << t_parallel << ", ";
std::cout << "Speed-up: " << t_serial/t_parallel << std::endl;
if (!std::equal(hist.begin(),hist.end(),hist_p.begin()))
std::cerr << "Parallel computation failed!!" << std::endl;
return 0;
}