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.

115 lines
2.1 KiB

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cmath>
  4. #include <omp.h>
  5. #include "Ttiming.h"
  6. using namespace std;
  7. void array_alloc(long **&arr, long arrsize)
  8. {
  9. try
  10. {
  11. arr = new long* [arrsize];
  12. arr[0] = new long [arrsize*arrsize];
  13. for(long i = 1; i < arrsize; ++i)
  14. arr[i] = arr[i-1] + arrsize;
  15. }
  16. catch (bad_alloc& ex)
  17. {
  18. cerr << "Could not allocate memory for array" << endl;
  19. exit(1);
  20. }
  21. }
  22. void array_destroy(long **arr)
  23. {
  24. delete [] arr[0];
  25. delete [] arr;
  26. }
  27. int main(int argc, char *argv[])
  28. {
  29. long **A=NULL, **B=NULL, **C=NULL;
  30. long rozmiar=0;
  31. char *endptr;
  32. int threads_num=0;
  33. TTiming tt;
  34. long i, j;//,k;
  35. if (argc < 3)
  36. {
  37. cerr << "Usage: " << argv[0] << " <n> <size>" << endl;
  38. exit(1);
  39. }
  40. rozmiar = strtol(argv[2], &endptr, 10);
  41. if (*endptr)
  42. {
  43. cerr << "Invalid array size format" << endl;
  44. exit(1);
  45. }
  46. if (rozmiar <= 0 || rozmiar > 2000)
  47. {
  48. cerr << "The number of matrix dimension must be in range [1,2000]" << endl;
  49. exit(1);
  50. }
  51. threads_num = strtol(argv[1], &endptr, 10);
  52. if (*endptr)
  53. {
  54. cerr << "Invalid number of threads format" << endl;
  55. exit(1);
  56. }
  57. if (threads_num <= 0)
  58. {
  59. cerr << "The number of threads must be positive" << endl;
  60. exit(1);
  61. }
  62. //ustawienie odpowiedniej ilosci watkow
  63. omp_set_num_threads(threads_num);
  64. //alokacja macierzy
  65. array_alloc(A, rozmiar);
  66. array_alloc(B, rozmiar);
  67. array_alloc(C, rozmiar);
  68. //wypelnienie macierzy A liczbami "losowymi"
  69. for (long i=0; i<rozmiar; ++i)
  70. for (long j=0; j<rozmiar; ++j)
  71. A[i][j] = (long)(sin(i) * i * j) % 10;
  72. //wypelnienie macierzy B liczbami "losowymi"
  73. for (long i=0; i<rozmiar; ++i)
  74. for (long j=0; j<rozmiar; ++j)
  75. B[i][j] = (long)(cos(j) *(i+j)) % 10;
  76. tt.Begin();
  77. //#pragma omp parallel for default(shared)
  78. #pragma omp parallel for default(none) shared(A, B, C) firstprivate(rozmiar)private(i, j)
  79. for (i=0; i<rozmiar; ++i)
  80. for (j=0; j<rozmiar; ++j)
  81. {
  82. C[i][j] = 0;
  83. for (long k=0; k<rozmiar; ++k)
  84. C[i][j] += A[i][k]*B[k][j];
  85. }
  86. long elapsed = tt.End();
  87. cout << "Time: " << elapsed << " ms" << endl;
  88. array_destroy(A);
  89. array_destroy(B);
  90. array_destroy(C);
  91. exit(0);
  92. }