fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #ifdef _OPENMP
  5. #include <omp.h>
  6. #endif
  7.  
  8. #define N 500 // Define the size of the matrix
  9.  
  10. void initializeMatrix(int matrix[N][N]) {
  11. for (int i = 0; i < N; i++) {
  12. for (int j = 0; j < N; j++) {
  13. matrix[i][j] = rand() % 10; // Random values between 0 and 9
  14. }
  15. }
  16. }
  17.  
  18. void printMatrix(int matrix[N][N]) {
  19. for (int i = 0; i < N; i++) {
  20. for (int j = 0; j < N; j++) {
  21. printf("%d ", matrix[i][j]);
  22. }
  23. printf("\n");
  24. }
  25. }
  26.  
  27. void multiplyMatrices(int A[N][N], int B[N][N], int C[N][N]) {
  28. #ifdef _OPENMP
  29. #pragma omp parallel for collapse(2)
  30. #endif
  31. for (int i = 0; i < N; i++) {
  32. for (int j = 0; j < N; j++) {
  33. C[i][j] = 0;
  34. for (int k = 0; k < N; k++) {
  35. C[i][j] += A[i][k] * B[k][j];
  36. }
  37. }
  38. }
  39. }
  40.  
  41. int main() {
  42. srand(time(0));
  43.  
  44. int A[N][N], B[N][N], C[N][N] = {0};
  45.  
  46. initializeMatrix(A);
  47. initializeMatrix(B);
  48.  
  49. double start, end;
  50. #ifdef _OPENMP
  51. start = omp_get_wtime();
  52. #else
  53. start = (double)clock() / CLOCKS_PER_SEC;
  54. #endif
  55.  
  56. multiplyMatrices(A, B, C);
  57.  
  58. #ifdef _OPENMP
  59. end = omp_get_wtime();
  60. #else
  61. end = (double)clock() / CLOCKS_PER_SEC;
  62. #endif
  63.  
  64. printf("Time taken for parallel matrix multiplication: %f seconds.\n", end - start);
  65.  
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0.21s 5292KB
stdin
Standard input is empty
stdout
Time taken for parallel matrix multiplication: 0.191500 seconds.