forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_quicksort.cpp
More file actions
79 lines (66 loc) · 2.52 KB
/
02_quicksort.cpp
File metadata and controls
79 lines (66 loc) · 2.52 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
70
71
72
73
74
75
76
77
78
79
#include <algorithm>
#include <chrono>
#include <future>
#include <list>
#include <random>
#include <ratio>
#include <stddef.h>
#include <stdio.h>
#include <vector>
#include <execution>
const size_t testSize = 100'000;
const int iterationCount = 5;
template <typename T> std::list<T> parallel_quick_sort(std::list<T> input) {
// Base Case
if (input.size() < 2) {
return input;
}
// select pivot
std::list<T> result;
result.splice(result.begin(), input, input.begin());
T pivot = *result.begin();
// partition the data
auto divide_point = std::partition(input.begin(), input.end(),
[&](T const &t) { return t < pivot; });
std::list<T> lower_list;
lower_list.splice(lower_list.end(), input, input.begin(), divide_point);
// =================================================================
// Example on how to parallelize divide and conquer algorithms.
// =================================================================
// recursion on the lower part, threading on the upper part.
auto new_lower(parallel_quick_sort(std::move(lower_list)));
std::future<std::list<T>> new_upper_future(
std::async(¶llel_quick_sort<T>, std::move(input)));
// return
result.splice(result.begin(), new_lower);
result.splice(result.end(), new_upper_future.get());
// =================================================================
return result;
}
void print_results(const char *const tag, const std::list<double> &sorted,
std::chrono::high_resolution_clock::time_point startTime,
std::chrono::high_resolution_clock::time_point endTime) {
printf("%s: Lowest: %g Highest: %g Time: %fms\n", tag, sorted.front(),
sorted.back(),
std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(
endTime - startTime)
.count());
}
int main() {
// generate some random doubles:
printf("Testing with %zu doubles...\n", testSize);
std::random_device rd;
std::list<double> doubles(testSize);
for (auto &d : doubles) {
d = static_cast<double>(rd());
}
for (int i = 0; i < iterationCount; ++i) {
std::list<double> sorted(doubles);
const auto startTime = std::chrono::high_resolution_clock::now();
// same sort call as above, but with par_unseq:
parallel_quick_sort(doubles);
const auto endTime = std::chrono::high_resolution_clock::now();
// in our output, note that these are the parallel results:
print_results("Parallel STL", sorted, startTime, endTime);
}
}