Guest User

Untitled

a guest
Nov 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <mpi.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5.  
  6. #define TRIALS 20
  7. #define ARRAY_SIZE 10000
  8.  
  9. int main (int argc, char *argv[])
  10. {
  11. int myid, numprocs;
  12. double startwtime, endwtime;
  13. int namelen;
  14. int* numbers = new int[ARRAY_SIZE];
  15. int i = 0, j = 0, max = 0;
  16. int s, s0, startIndex, endIndex;
  17. double totalTime;
  18. MPI_Status stat;
  19.  
  20. char processor_name[MPI_MAX_PROCESSOR_NAME];
  21.  
  22. MPI_Init(&argc, &argv);
  23. MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  24. MPI_Comm_rank(MPI_COMM_WORLD, &myid);
  25. MPI_Get_processor_name(processor_name, &namelen);
  26.  
  27. fprintf(stderr, "Process %d on $s\n", myid, processor_name);
  28. fflush(stderr);
  29.  
  30. if (myid == 0)
  31. {
  32. s = (int) floor(ARRAY_SIZE/numprocs);
  33. s0 = s + ARRAY_SIZE%numprocs;
  34.  
  35. for (i = 0; i < ARRAY_SIZE; i++)
  36. {
  37. numbers[i] = i;
  38. }
  39.  
  40. for (j = 1; j < numprocs; j++)
  41. {
  42. MPI_Send(&numbers, ARRAY_SIZE, MPI_INT, j, 1, MPI_COMM_WORLD);
  43. MPI_Send(&s, ARRAY_SIZE, MPI_INT, j, 2, MPI_COMM_WORLD);
  44. MPI_Send(&s0, ARRAY_SIZE, MPI_INT, j, 3, MPI_COMM_WORLD);
  45. MPI_Send(&max, ARRAY_SIZE, MPI_INT, j, 4, MPI_COMM_WORLD);
  46. }
  47. }
  48.  
  49. startIndex = s0 + (myid - 1)*s;
  50. endIndex = startIndex + s;
  51.  
  52. totalTime = 0;
  53.  
  54. for (j = 1; j <= TRIALS; j++)
  55. {
  56. if (myid == 0)
  57. {
  58. for (i = 0; i < s0; i++)
  59. {
  60. if (max < numbers[i])
  61. {
  62. max = numbers[i];
  63. }
  64. }
  65. }
  66. else
  67. {
  68. for (i = startIndex; i < endIndex; i++)
  69. {
  70. if (max < numbers[i])
  71. {
  72. max = numbers[i];
  73. }
  74. }
  75. }
  76.  
  77. MPI_Recv(&numbers, ARRAY_SIZE, MPI_INT, i, 1, MPI_COMM_WORLD, &stat);
  78. MPI_Recv(&s, ARRAY_SIZE, MPI_INT, i, 2, MPI_COMM_WORLD, &stat);
  79. MPI_Recv(&s0, ARRAY_SIZE, MPI_INT, i, 3, MPI_COMM_WORLD, &stat);
  80. MPI_Recv(&max, ARRAY_SIZE, MPI_INT, i, 4, MPI_COMM_WORLD, &stat);
  81.  
  82. if (myid == 0)
  83. {
  84. double runTime;
  85. endwtime = MPI_Wtime();
  86. runTime = endwtime - startwtime;
  87.  
  88. printf("Trial %d : Execution time (sec) = %f\n", j, runTime);
  89. printf("Max = %d \n", max);
  90. totalTime += runTime;
  91. }
  92. }
  93.  
  94. MPI_Finalize();
  95.  
  96. if (myid == 0)
  97. printf("Average time efor %d trials = %f\n", TRIALS, totalTime/TRIALS);
  98. }
Add Comment
Please, Sign In to add comment