fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. int main(int argc, char **argv){
  6. MPI_Init(NULL, NULL);
  7. int num_procs;
  8. MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
  9. int rank;
  10. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  11. if (rank == 0){
  12. int n;
  13. printf("Enter number of elements : ");
  14. scanf("%d", &n);
  15. int arr[n];
  16. for (int i = 0; i < n; i++){
  17. arr[i] = rand() % 10000 + 1;
  18. }
  19. printf("Array is -\n [ ");
  20. for (int i = 0; i < n; i++){
  21. printf("%d ", arr[i]);
  22. }
  23. printf("]\n");
  24. int elem_to_send = n / 2;
  25. if (n % 2)
  26. elem_to_send++;
  27. // send the size
  28. MPI_Send(&elem_to_send, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
  29. // send the array
  30. MPI_Send(&arr[n / 2], elem_to_send, MPI_INT, 1, 1, MPI_COMM_WORLD);
  31. float t1 = clock();
  32. int local = 0;
  33. for (int i = 0; i < n / 2; i++)
  34. local = local + arr[i];
  35. int s_rec = 0;
  36. float t2 = clock();
  37. printf("Time taken by process %d : %f\n", rank, (t2 - t1) / CLOCKS_PER_SEC);
  38. MPI_Recv(&s_rec, 1, MPI_INT, 1, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  39. local = local + s_rec;
  40. printf("Total sum of array is %d\n", local);
  41. }else{
  42. float t1 = clock();
  43. int size;
  44. MPI_Recv(&size, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  45. int arr[size];
  46. MPI_Recv(arr, size, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  47. float t2 = clock();
  48. printf("Total time for recieving : %f", (t2 - t1) / CLOCKS_PER_SEC);
  49. t1 = clock();
  50. int local = 0;
  51. for (int i = 0; i < size; i++)
  52. local = local + arr[i];
  53. printf("\nProcess %d sending sum %d back to main...\n", rank, local);
  54. t2 = clock();
  55. printf("Time taken by process for addition %d : %f\n", rank, (t2 - t1)/CLOCKS_PER_SEC);
  56. MPI_Send(&local, 1, MPI_INT, 0, 2, MPI_COMM_WORLD);
  57. }
  58. MPI_Finalize();
  59. }
Success #stdin #stdout #stderr 0.24s 40956KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted