Advertisement
Guest User

pa2

a guest
Jun 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "mpi.h"
  4.  
  5. int main(int argc, char *argv[]) {
  6. int numtasks, rank, N;
  7. int result=0;
  8. int product;
  9.  
  10. int* a;
  11. int* b;
  12.  
  13. //initializing MPI
  14. MPI_Init(&argc, &argv);
  15. //get size
  16. MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
  17. //get rank
  18. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  19. //have to broadcast N still to distribute it
  20. MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
  21.  
  22. if(rank == 0) {
  23. N = 100; //simulate reading in user input
  24. }
  25. //if(rank == 0) {
  26. // printf("Enter size: %d\n", N);
  27. // scanf("%d", &N);
  28. //}
  29. if(rank == 0) {
  30. //pointers to dynamically allocate memory for 2 arrays on each node. done in master thread
  31. a=(int*)malloc(N*sizeof(int));
  32. b=(int*)malloc(N*sizeof(int));
  33. //hardcoding each value of vectors to 2
  34. for(int i = 0; i < N; i++) {
  35. a[i]=b[i]=2;
  36. }
  37. }
  38. int new_N; //new_N: new discrete variable to sum counts
  39. if(rank < (N%numtasks)) {
  40. new_N = N/numtasks + 1;
  41. }
  42. else {
  43. new_N = N/numtasks;
  44. }
  45.  
  46. //array to hold count for each rank
  47. int* sendcount = (int*)malloc(N*sizeof(int));
  48. //array that holds displacement from start of sendbuf to take the data
  49. int* displs = (int*)malloc(N*sizeof(int));
  50.  
  51. //fill sendcount array
  52. for(int i = 0; i < new_N; i++) {
  53. sendcount[i] = new_N;
  54. displs[i] = i*sendcount[i];
  55. }
  56. //takes care of remainder
  57. for(int i = N%numtasks; i < numtasks; i++) {
  58. sendcount[i] = N/numtasks;
  59. displs[i] = i*sendcount[i];
  60. }
  61.  
  62. MPI_Scatterv(a, sendcount, displs, MPI_INT, a, new_N, MPI_INT, 0, MPI_COMM_WORLD);
  63. MPI_Scatterv(b, sendcount, displs, MPI_INT, a, new_N, MPI_INT, 0, MPI_COMM_WORLD);
  64.  
  65. //actually calculating dot product
  66. for(int i = 0; i < N; i++){
  67. result+=(a[i] * b[i]);
  68. }
  69. printf("%d\n", rank);
  70. //collect individual sums from processors for final result
  71. MPI_Allreduce(MPI_IN_PLACE, &result, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
  72. printf("Rank: %d: Result: %d\n", rank, result);
  73. //finished with MPI
  74. MPI_Finalize();
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement