You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
2.3 KiB

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cmath>
  4. #include "Ttiming.h"
  5. #include <mpi.h>
  6. #include <stdio.h>
  7. using namespace std;
  8. void array_alloc(long **&arr, long arrsize)
  9. {
  10. try
  11. {
  12. arr = new long* [arrsize];
  13. arr[0] = new long [arrsize*arrsize];
  14. for(long i = 1; i < arrsize; ++i)
  15. arr[i] = arr[i-1] + arrsize;
  16. }
  17. catch (bad_alloc& ex)
  18. {
  19. cerr << "Could not allocate memory for array" << endl;
  20. exit(1);
  21. }
  22. }
  23. void array_destroy(long **arr)
  24. {
  25. delete [] arr[0];
  26. delete [] arr;
  27. }
  28. int main(int argc, char *argv[])
  29. {
  30. long **A=NULL, **B=NULL, **C=NULL, **B_rot=NULL;
  31. long rozmiar=0;
  32. char *endptr;
  33. TTiming tt;
  34. long i, j;//,k;
  35. MPI::Status status;
  36. if (argc < 2)
  37. {
  38. cerr << "Usage: " << argv[0] << " <size>" << endl;
  39. exit(1);
  40. }
  41. rozmiar = strtol(argv[1], &endptr, 10);
  42. if (*endptr)
  43. {
  44. cerr << "Invalid array size format" << endl;
  45. exit(1);
  46. }
  47. if (rozmiar <= 0 || rozmiar > 2000)
  48. {
  49. cerr << "The number of matrix dimension must be in range [1,2000]" << endl;
  50. exit(1);
  51. }
  52. MPI::Init(argc, argv);
  53. int taskid = MPI::COMM_WORLD.Get_rank();
  54. int ntasks = MPI::COMM_WORLD.Get_size();
  55. printf("ntasks= %d : taskid= %d : Hello World!\n",ntasks,taskid);
  56. //alokacja macierzy
  57. array_alloc(A, rozmiar);
  58. if (taskid == 0)
  59. {
  60. array_alloc(B, rozmiar);
  61. array_alloc(B_rot, rozmiar);
  62. }
  63. array_alloc(C, rozmiar);
  64. if (taskid == 0)
  65. {
  66. //wypelnienie macierzy A liczbami "losowymi"
  67. for (long i=0; i<rozmiar; ++i)
  68. for (long j=0; j<rozmiar; ++j)
  69. A[i][j] = (long)(sin(i) * i * j) % 10;
  70. //wypelnienie macierzy B liczbami "losowymi"
  71. for (long i=0; i<rozmiar; ++i)
  72. for (long j=0; j<rozmiar; ++j)
  73. B[i][j] = (long)(cos(j) *(i+j)) % 10;
  74. //dokonaj obracania macierzy
  75. for (long i=0; i<rozmiar; ++i)
  76. for (long j=0; j<rozmiar; ++j)
  77. B_rot[i][j] = B[j][i];
  78. }
  79. //wysyłanie macierzy A do wszystkich
  80. MPI::COMM_WORLD.Bcast(&A[0][0], rozmiar*rozmiar, MPI::LONG, 0);
  81. /*
  82. tt.Begin();
  83. for (i=0; i<rozmiar; ++i)
  84. for (j=0; j<rozmiar; ++j)
  85. {
  86. C[i][j] = 0;
  87. for (long k=0; k<rozmiar; ++k)
  88. C[i][j] += A[i][k]*B[k][j];
  89. }
  90. long elapsed = tt.End();
  91. cout << "Time: " << elapsed << " ms" << endl;
  92. array_destroy(A);
  93. array_destroy(B);
  94. array_destroy(C);
  95. */
  96. cout << taskid << ": " << A[2][2] << endl;
  97. MPI::Finalize();
  98. exit(0);
  99. }