fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <ctime>
  5. #include <omp.h>
  6.  
  7. #define N 5 // Set a small value (e.g., N=5) for readable output
  8.  
  9. using namespace std;
  10.  
  11. // Function to generate a random matrix
  12. void generateMatrix(vector<vector<int>>& matrix) {
  13. for (int i = 0; i < N; i++) {
  14. for (int j = 0; j < N; j++) {
  15. matrix[i][j] = rand() % 10; // Random values from 0 to 9
  16. }
  17. }
  18. }
  19.  
  20. // Function to print a matrix
  21. void printMatrix(const vector<vector<int>>& matrix, const string& name) {
  22. cout << name << " Matrix:\n";
  23. for (int i = 0; i < N; i++) {
  24. for (int j = 0; j < N; j++) {
  25. cout << matrix[i][j] << " ";
  26. }
  27. cout << endl;
  28. }
  29. cout << endl;
  30. }
  31.  
  32. // Function to multiply matrices using OpenMP
  33. void multiplyMatrices(const vector<vector<int>>& A, const vector<vector<int>>& B, vector<vector<int>>& C) {
  34. #pragma omp parallel for collapse(2)
  35. for (int i = 0; i < N; i++) {
  36. for (int j = 0; j < N; j++) {
  37. C[i][j] = 0;
  38. for (int k = 0; k < N; k++) {
  39. C[i][j] += A[i][k] * B[k][j];
  40. }
  41. }
  42. }
  43. }
  44.  
  45. int main() {
  46. srand(time(0));
  47.  
  48. vector<vector<int>> A(N, vector<int>(N));
  49. vector<vector<int>> B(N, vector<int>(N));
  50. vector<vector<int>> C(N, vector<int>(N, 0));
  51.  
  52. generateMatrix(A);
  53. generateMatrix(B);
  54.  
  55. if (N <= 10) { // Print only if N is small to avoid large output
  56. printMatrix(A, "A");
  57. printMatrix(B, "B");
  58. }
  59.  
  60. clock_t start = clock(); // Use clock() instead of omp_get_wtime()
  61.  
  62. multiplyMatrices(A, B, C);
  63.  
  64. clock_t end = clock(); // End time
  65.  
  66. if (N <= 10) { // Print result matrix only if N is small
  67. printMatrix(C, "C");
  68. }
  69.  
  70. double time_taken = double(end - start) / CLOCKS_PER_SEC;
  71. cout << "Matrix multiplication completed in " << time_taken << " seconds." << endl;
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
A Matrix:
9 1 9 1 4 
1 8 2 8 6 
9 0 2 2 0 
9 0 3 7 5 
4 7 8 6 9 

B Matrix:
3 3 6 4 4 
8 3 5 7 6 
1 0 5 6 0 
3 5 1 5 7 
1 6 7 4 5 

C Matrix:
51 59 133 118 69 
99 103 106 136 138 
35 37 66 58 50 
56 92 111 109 110 
103 117 168 179 145 

Matrix multiplication completed in 0 seconds.