Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
92 lines (74 loc) · 2.26 KB
/
Copy pathmain.cpp
File metadata and controls
92 lines (74 loc) · 2.26 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
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
bool readMatrix(const string& filename, vector<double>& matrix, int& n) {
ifstream in(filename);
if (!in.is_open()) return false;
in >> n;
matrix.resize(n * n);
for (int i = 0; i < n * n; ++i) {
in >> matrix[i];
}
return true;
}
void saveMatrix(const string& filename, const vector<double>& matrix, int n) {
ofstream out(filename);
out << n << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
out << fixed << setprecision(6) << matrix[i * n + j] << " ";
}
out << endl;
}
}
int main(int argc, char* argv[]) {
if (argc < 4) {
cout << "Usage: " << argv[0] << " <input1> <input2> <output> [threads]" << endl;
return 1;
}
string fileA = argv[1];
string fileB = argv[2];
string fileRes = argv[3];
int numThreads = (argc > 4) ? stoi(argv[4]) : 1;
int n1, n2;
vector<double> A, B;
if (!readMatrix(fileA, A, n1) || !readMatrix(fileB, B, n2)) {
cerr << "Error reading input files!" << endl;
return 1;
}
if (n1 != n2) {
cerr << "Matrices must be of the same size!" << endl;
return 1;
}
int n = n1;
vector<double> C(n * n, 0.0);
// Установка количества потоков
#ifdef _OPENMP
omp_set_num_threads(numThreads);
#endif
auto start = chrono::high_resolution_clock::now();
// Перемножение матриц
#pragma omp parallel for collapse(2)
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
double sum = 0;
for (int k = 0; k < n; ++k) {
sum += A[i * n + k] * B[k * n + j];
}
C[i * n + j] = sum;
}
}
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> diff = end - start;
saveMatrix(fileRes, C, n);
cout << "Task size (N): " << n << endl;
cout << "Threads: " << numThreads << endl;
cout << "Execution time: " << diff.count() << " seconds" << endl;
return 0;
}