C++ Library Extensions 2022.12.09
To help learn modern C++ programming
044-parallel.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
3#include <execution>
4
6auto nl = tpf::nl;
8
9namespace fcp
10{
11 template<typename ElementType>
13 {
14 public:
15 using element_type = ElementType;
16
17 private:
18 element_type m_x, m_y, m_z, m_color;
19
20 public:
22
24 m_x{x}, m_y{y}, m_z{z} { }
25
26 friend vector_3d operator* (const vector_3d& L, const vector_3d& R)
27 {
28 return { L.m_y * R.m_z - L.m_z * R.m_y,
29 L.m_z * R.m_x - L.m_x * R.m_z,
30 L.m_x * R.m_y - L.m_y * R.m_x };
31 }
32
33 friend std::ostream& operator<<(std::ostream& os, const vector_3d& v)
34 {
35 os << "< " << v.m_x <<", " << v.m_y <<", " << v.m_z <<" >";
36 return os;
37 }
38 };
39
40} // end of fcp
41
43{
44 fcp::vector_3d<double> v1{1, 0, 0}, v2{0, 1, 0}, v3{0, 0, 1};
45
46 stream << "v1 = " << v1 << endl;
47 stream << "v2 = " << v2 << endl;
48 stream << "v3 = " << v3 << endl;
49
50 auto a1 = v1 * v2;
51
52 auto a2 = v2 * v3;
53 auto a3 = v3 * v1;
54
55 stream << "a1 = " << a1 << endl;
56 stream << "a2 = " << a2 << endl;
57 stream << "a3 = " << a3 << endl;
58}
59
60template<typename Policy>
61void performance_test(Policy policy, size_t test_count, size_t element_count)
62{
63 std::vector<fcp::vector_3d<float>> points;
64 points.reserve(element_count);
65
66 auto generator = tpf::chrono_random::random_generator<float>(-10, +10);
67
68 fcp::vector_3d<float> r {generator(), generator(), generator()};
69
70 for(size_t i = 0; i < element_count; ++i)
71 points.emplace_back(generator(), generator(), generator());
72
73 for(size_t i = 0; i < test_count; ++i)
74 {
76
77 std::transform(policy, points.begin(), points.end(), points.begin(),
78 [&r](const auto& l){ return l * r; });
79
80 stream << "Elapsed: "<< sw.elapsed_time() << nl << endl;
81 }
82}
83
84int main()
85{
86 size_t element_count = 100'000'000;
87
88 stream <<"Sequential - \n";
89 performance_test(std::execution::seq, 5, element_count);
90
91 stream <<"Parallel - \n";
92 performance_test(std::execution::par, 5, element_count);
93
94 stream <<"Parallel Vectorized - \n";
95 performance_test(std::execution::par_unseq, 5, element_count);
96
97}
void test_vector_operation()
tpf::sstream stream
Definition: 044-parallel.cpp:5
void performance_test(Policy policy, size_t test_count, size_t element_count)
auto endl
Definition: 044-parallel.cpp:7
auto nl
Definition: 044-parallel.cpp:6
int main()
vector_3d(element_type x, element_type y, element_type z)
friend std::ostream & operator<<(std::ostream &os, const vector_3d &v)
friend vector_3d operator*(const vector_3d &L, const vector_3d &R)
ElementType element_type
std::string elapsed_time(bool bReset=true, TimeUnit dummy_time=TimeUnit{}) const
constexpr auto endl
Definition: tpf_output.hpp:973
constexpr auto nl
Definition: tpf_output.hpp:971
Stream output operators << are implemented.