fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <iomanip>
  4. #include <mpi.h>
  5.  
  6. using namespace std;
  7.  
  8. int main(int argc, char** argv) {
  9. MPI_Init(&argc, &argv);
  10. int rank, size;
  11. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  12. MPI_Comm_size(MPI_COMM_WORLD, &size);
  13.  
  14. const int NRA = 4, NCA = 3, NCB = 2; // Example dimensions of matrices
  15. const int MASTER = 0;
  16. double start_time;
  17. start_time = MPI_Wtime();
  18.  
  19. double *a = nullptr;
  20. double *b = new double[NCA * NCB];
  21. double *c = new double[NRA * NCB];
  22.  
  23. if (rank == MASTER) {
  24. cout << "Number of processes: " << size << endl;
  25. cout << "Matrix A" << endl;
  26. a = new double[NRA * NCA];
  27. for (int i = 0; i < NRA; i++) {
  28. for (int j = 0; j < NCA; j++) {
  29. a[i * NCA + j] = 1 + i + j; // Example initialization
  30. cout << setw(5) << a[i * NCA + j] << " ";
  31. }
  32. cout << endl;
  33. }
  34.  
  35. cout << "Matrix B" << endl;
  36. for (int i = 0; i < NCA; i++) {
  37. for (int j = 0; j < NCB; j++) {
  38. b[i * NCB + j] = 1 + i * j; // Example initialization
  39. cout << setw(5) << b[i * NCB + j] << " ";
  40. }
  41. cout << endl;
  42. }
  43. }
  44.  
  45. // Broadcast Matrix B to all processes
  46. MPI_Bcast(b, NCA * NCB, MPI_DOUBLE, MASTER, MPI_COMM_WORLD);
  47.  
  48. // Allocate memory for Matrix A on all processes
  49. if (rank != MASTER) {
  50. a = new double[NRA * NCA];
  51. }
  52.  
  53. // Broadcast Matrix A to all processes
  54. MPI_Bcast(a, NRA * NCA, MPI_DOUBLE, MASTER, MPI_COMM_WORLD);
  55.  
  56. // Perform matrix multiplication
  57. for (int i = 0; i < NRA; i++) {
  58. for (int j = 0; j < NCB; j++) {
  59. c[i * NCB + j] = 0;
  60. for (int k = 0; k < NCA; k++) {
  61. c[i * NCB + j] += a[i * NCA + k] * b[k * NCB + j];
  62. }
  63. }
  64. }
  65.  
  66. // Master process prints the resulting matrix C
  67. if (rank == MASTER) {
  68. cout << "Matrix C" << endl;
  69. for (int i = 0; i < NRA; i++) {
  70. for (int j = 0; j < NCB; j++) {
  71. cout << setw(5) << c[i * NCB + j] << " ";
  72. }
  73. cout << endl;
  74. }
  75. }
  76.  
  77. // Free allocated memory
  78. delete[] b;
  79. delete[] c;
  80. if (rank == MASTER) {
  81. delete[] a;
  82. }
  83.  
  84. MPI_Finalize();
  85. return 0;
  86. }
  87.  
Success #stdin #stdout #stderr 0.23s 40632KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "using namespace"
Execution halted