Advertisement
Guest User

Untitled

a guest
Dec 14th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1.  
  2. /* This is the block-row partitioned version */
  3. /* I already wrote some parts of the code */
  4. #include <mpi.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include<iostream>
  8.  
  9. using namespace std;
  10.  
  11. #define SIZE1 64
  12. #define SIZE2 128
  13. #define SIZE3 64
  14.  
  15. double a[SIZE1][SIZE2];
  16. double b[SIZE2][SIZE3];
  17.  
  18. double c[SIZE1][SIZE3]; // c = a * b
  19.  
  20. int main(int argc, char *argv[]){
  21. int i,j,k;
  22. int rank; // process rank
  23. int size; // number of processes
  24. FILE *myfile1, *myfile2, *myfile3;
  25.  
  26. // read array a from file a.txt
  27. myfile1 = fopen("a.txt", "r");
  28. MPI_Init(&argc, &argv);
  29. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  30. MPI_Comm_size(MPI_COMM_WORLD, &size);
  31.  
  32. if(rank==0){
  33. // read array a from a.txt file
  34. myfile1 = fopen("a.txt", "r");
  35. for(i=0; i<SIZE1; i++)
  36. for(j=0; j<SIZE2; j++)
  37. fscanf(myfile1,"%lf",&a[i][j]);
  38. fclose(myfile1);
  39.  
  40. // read array b from b.txt file
  41. myfile2 = fopen("b.txt", "r");
  42. for(i=0; i<SIZE2; i++)
  43. for(j=0; j<SIZE3; j++)
  44. fscanf(myfile2,"%lf",&b[i][j]);
  45. fclose(myfile2);
  46. }
  47.  
  48. //SIZE1 -> a rows // SIZE2 -> a columns b rows // SIZE3 -> b columns
  49. int chunk = SIZE1/size; //size =2 -> chunk = 2 -> tmp[2][8] * b[8][4] -> tmp[2][4];
  50.  
  51. double tmp[chunk][SIZE3];
  52.  
  53. if(rank==0) {
  54. //MPI_Scatter (sendbuf, sendcnt, sendtype,recvbuf, recvcnt, recvtype, root, comm)
  55. MPI_Scatter(a, chunk * SIZE2, MPI_DOUBLE, tmp, chunk * SIZE2, MPI_DOUBLE, 0, MPI_COMM_WORLD);
  56. }
  57.  
  58. for(i=0; i<chunk; i++){
  59. for(j=0; j<chunk; j++){
  60. tmp[i][j] = 0;
  61. for(k=0; k<SIZE2; k++)
  62. tmp[i][j] += a[i][k] * b[k][j];
  63. }
  64. }
  65.  
  66. //MPI_Gather (sendbuf, sendcnt, sendtype,recvbuf, recvcnt, recvtype, root, comm)
  67. MPI_Gather (tmp, chunk * SIZE2, MPI_DOUBLE, c, chunk * SIZE2, MPI_DOUBLE, 0, MPI_COMM_WORLD);
  68.  
  69. if(rank==0){
  70. //write array c to c.txt file
  71. myfile3 = fopen("c.txt","wb");
  72. for(i=0; i<SIZE1; i++){
  73. for(j=0; j<SIZE3; j++)
  74. fprintf(myfile3, "%lf ",c[i][j]);
  75. fprintf(myfile3, "\n");
  76. }
  77. fclose(myfile3);
  78. }
  79.  
  80. MPI_Finalize();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement