(2)Parallel Basisversion erstellt

This commit is contained in:
Kai Graap 2025-12-15 15:22:41 +01:00
parent a3b771f60d
commit a9cbe6ea7d
2 changed files with 37 additions and 14 deletions

View File

@ -52,3 +52,4 @@ if (APPLE)
target_link_libraries(Prog3B "-framework Cocoa")
target_link_libraries(Prog3B "-framework OpenGL")
endif()

View File

@ -1,7 +1,7 @@
#include <iostream>
#include <vector>
#include <chrono>
#include <omp.h>
// Funktion erzeugt zwei Matrizen A und B der Größe n x n mit Zufallswerten
@ -27,17 +27,14 @@ void generateRandomMatrices(int n,
}
}
// Matrizenmultiplikation
std::vector<std::vector<double>> matmul(const std::vector<std::vector<double>>& A,
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();
if (A[0].size() != B.size())
throw std::runtime_error("Matrixgrößen passen nicht.");
std::vector<std::vector<double>> C(n, std::vector<double>(m, 0.0));
for (int i = 0; i < n; ++i)
@ -48,22 +45,47 @@ std::vector<std::vector<double>> matmul(const std::vector<std::vector<double>>&
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;
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(A, B);
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";
std::chrono::duration<double> duration = end - start;
std::cout << "Serielle Laufzeit bei " << N << "x" << N
<< ": " << duration.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;
}
}