Prog3/parallel/matrizenmultiplikation.cpp

92 lines
2.6 KiB
C++

#include <iostream>
#include <vector>
#include <chrono>
#include <omp.h>
// Funktion erzeugt zwei Matrizen A und B der Größe n x n mit Zufallswerten
void generateRandomMatrices(int n,
std::vector<std::vector<double>>& A,
std::vector<std::vector<double>>& B,
double min_val = 0.0,
double max_val = 10.0)
{
// Zufallsgenerator initialisieren
std::srand(static_cast<unsigned int>(std::time(nullptr)));
A.resize(n, std::vector<double>(n));
B.resize(n, std::vector<double>(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
{
double r1 = static_cast<double>(std::rand()) / RAND_MAX; // 0..1
double r2 = static_cast<double>(std::rand()) / RAND_MAX; // 0..1
A[i][j] = min_val + r1 * (max_val - min_val);
B[i][j] = min_val + r2 * (max_val - min_val);
}
}
std::vector<std::vector<double>> matmul_serial(
const std::vector<std::vector<double>>& A,
const std::vector<std::vector<double>>& B)
{
int n = A.size();
int m = B[0].size();
int p = B.size();
std::vector<std::vector<double>> C(n, std::vector<double>(m, 0.0));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
for (int k = 0; k < p; ++k)
C[i][j] += A[i][k] * B[k][j];
return C;
}
std::vector<std::vector<double>> matmul_parallel(
const std::vector<std::vector<double>>& A,
const std::vector<std::vector<double>>& B)
{
int n = A.size();
int m = B[0].size();
int p = B.size();
std::vector<std::vector<double>> C(n, std::vector<double>(m, 0.0));
#pragma omp parallel for
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
for (int k = 0; k < p; ++k)
C[i][j] += A[i][k] * B[k][j];
return C;
}
int main()
{
int N = 500;
std::vector<std::vector<double>> A, B;
generateRandomMatrices(N, A, B);
// Serielle Version
auto start = std::chrono::high_resolution_clock::now();
auto C_serial = matmul_serial(A, B);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Serielle Laufzeit: "
<< std::chrono::duration<double>(end - start).count()
<< " Sekunden\n";
// Parallele Version
start = std::chrono::high_resolution_clock::now();
auto C_parallel = matmul_parallel(A, B);
end = std::chrono::high_resolution_clock::now();
std::cout << "Parallele Laufzeit: "
<< std::chrono::duration<double>(end - start).count()
<< " Sekunden\n";
return 0;
}