-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixMultiply.cpp
76 lines (66 loc) · 2.42 KB
/
MatrixMultiply.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
#include <cmath>
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include "parallel.h"
void fillMatrix(std::vector<std::vector<double>> &matrix) {
std::size_t length = matrix.size();
std::mt19937 generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
for (std::size_t i = 0; i < length; ++i) {
for (std::size_t j = 0; j < length; ++j) {
matrix[i][j] = distribution(generator);
}
}
}
int main() {
std::cout << "Parallel Framework: " << PARALLEL_FRAMEWORK << std::endl;
std::size_t length(1000);
std::vector<std::vector<double>> a(length, std::vector<double>(length)),
b(length, std::vector<double>(length)),
c(length, std::vector<double>(length));
fillMatrix(a);
fillMatrix(b);
std::chrono::high_resolution_clock::time_point t1 =
std::chrono::high_resolution_clock::now();
parallel_for_each(par, 0, length, [&a, &b, &c, length](std::size_t i) {
for (std::size_t j = 0; j < length; ++j) {
for (std::size_t k = 0; k < length; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
});
std::chrono::high_resolution_clock::time_point t2 =
std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span =
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "It took me " << time_span.count() << " seconds." << std::endl;
std::cout << "serial fallback: " << std::endl;
t1 = std::chrono::high_resolution_clock::now();
parallel_for_each(seq, 0, length, [&a, &b, &c, length](std::size_t i) {
for (std::size_t j = 0; j < length; ++j) {
for (std::size_t k = 0; k < length; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
});
t2 = std::chrono::high_resolution_clock::now();
time_span =
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "It took me " << time_span.count() << " seconds." << std::endl;
std::cout << "serial old: " << std::endl;
t1 = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < length; ++i) {
for (std::size_t j = 0; j < length; ++j) {
for (std::size_t k = 0; k < length; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
t2 = std::chrono::high_resolution_clock::now();
time_span =
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "It took me " << time_span.count() << " seconds." << std::endl;
return 0;
}