fork download
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <random>
  4. #include <sys/time.h>
  5. using namespace std;
  6.  
  7. struct ThreadData
  8. {
  9. int **arr;
  10. int startRow, endRow, n;
  11. int *sums;
  12. };
  13.  
  14. void* calculate_summ(void *arg)
  15. {
  16. ThreadData* data = (ThreadData*)arg;
  17.  
  18. for(int i = data->startRow; i < data->endRow; i++)
  19. {
  20. data->sums[i] = 0;
  21. for(int j = 0; j < data->n; j++)
  22. {
  23. if(data->arr[i][j] > 0)
  24. {
  25. data->sums[i] += data->arr[i][j];
  26. }
  27. }
  28. }
  29. return NULL;
  30. }
  31.  
  32. struct timeval tv1;
  33. void time_start()
  34. {
  35. struct timezone tz;
  36. gettimeofday(&tv1, &tz);
  37. }
  38.  
  39. long time_stop()
  40. {
  41. struct timeval tv2, dtv;
  42. struct timezone tz;
  43. gettimeofday(&tv2, &tz);
  44. dtv.tv_sec= tv2.tv_sec -tv1.tv_sec;
  45. dtv.tv_usec=tv2.tv_usec-tv1.tv_usec;
  46. if(dtv.tv_usec<0)
  47. {
  48. dtv.tv_sec--;
  49. dtv.tv_usec+=1000000;
  50. }
  51. return dtv.tv_sec*1000000+dtv.tv_usec;
  52. }
  53.  
  54. int main()
  55. {
  56. srand(time(0));
  57.  
  58. int n = 100, m = 100, k = 2;
  59.  
  60. int** arr = new int*[n];
  61. for(int i = 0; i < n; i++)
  62. {
  63. arr[i] = new int[m];
  64. }
  65. for(int i = 0; i < n; i++)
  66. {
  67. for(int j = 0; j < m; j++)
  68. {
  69. arr[i][j] = rand()%15-5;
  70. }
  71. }
  72. /*
  73.   for(int i = 0; i < n; i++)
  74.   {
  75.   for(int j = 0; j < m; j++)
  76.   {
  77.   cout << arr[i][j] << " ";
  78.   }
  79.   cout << endl;
  80.   }
  81.   */
  82. int thread_num = n/k, ostatok = n%k, sums[n];
  83.  
  84. time_start();
  85.  
  86. pthread_t* threads = new pthread_t[thread_num];
  87. ThreadData* threadData = new ThreadData[thread_num];
  88.  
  89. for(int i = 0; i < thread_num; i++)
  90. {
  91. threadData[i].n = n;
  92. threadData[i].startRow = i*k;
  93. threadData[i].endRow = threadData[i].startRow + k;
  94. threadData[i].arr = arr;
  95. threadData[i].sums = sums;
  96.  
  97. pthread_create(&threads[i], NULL, calculate_summ, (void*)&threadData[i]);
  98. }
  99.  
  100. for(int i = 0; i < ostatok; i++) {
  101. threadData[i].endRow += 1;
  102. }
  103.  
  104. for(int i = 0; i < thread_num; i++)
  105. {
  106. pthread_join(threads[i], NULL);
  107. }
  108. /*
  109.   cout << "sums: ";
  110.   for(int i = 0; i < n; i++)
  111.   {
  112.   cout << sums[i] << " ";
  113.   }
  114.   */
  115. cout << "\nPARAL_GROUP: Time: " << time_stop() << endl;
  116.  
  117. for(int i = 0; i < n; i++)
  118. {
  119. delete[] arr[i];
  120. }
  121. delete[] arr;
  122. delete[] threads;
  123. delete[] threadData;
  124. }
  125.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
PARAL_GROUP: Time: 534