]> vgcfreebox.myrthtech.pt Git - ue-pp-squarematrixparallelisation.git/blob - ParallelMatrixSearch.c
improving matrix init
[ue-pp-squarematrixparallelisation.git] / ParallelMatrixSearch.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <time.h>
5
6 const int m_rows = 40000;
7 const int m_cols = m_rows;
8
9 _Atomic int hv = 0;
10 int **matrix;
11
12 typedef struct{
13 int start;
14 int end;
15 } thread_args;
16
17 void* parallel_search_cols(void *arg){
18 thread_args *args = (thread_args *)arg;
19 for(int r = 0; r < m_rows; r++){
20 for(int c = args->start; c < args->end; c++){
21 if(matrix[r][c] > hv){
22 hv = matrix[r][c];
23 }
24 }
25 }
26 return NULL;
27 }
28
29 void run_parallel_search(int num_threads) {
30 pthread_t *threads = malloc(num_threads * sizeof(pthread_t));
31 thread_args *args = malloc(num_threads * sizeof(thread_args));
32
33 if (threads == NULL || args == NULL) {
34 perror("Failed to allocate memory for threads");
35 exit(1);
36 }
37
38 int chunk_size = m_cols / num_threads;
39
40 for (int i = 0; i < num_threads; i++) {
41 args[i].start = i * chunk_size;
42 if (i == num_threads - 1) {
43 args[i].end = m_cols;
44 } else {
45 args[i].end = (i + 1) * chunk_size;
46 }
47 if (pthread_create(&threads[i], NULL, &parallel_search_cols, &args[i]) != 0) {
48 perror("Failed to create thread");
49 exit(1);
50 }
51 }
52
53 for (int i = 0; i < num_threads; i++) {
54 pthread_join(threads[i], NULL);
55 }
56 free(threads);
57 free(args);
58 }
59
60 int main(void){
61 printf("1st --> Allocate memory\n");
62 clock_t t_t1; t_t1 = clock();
63 size_t rows_size = m_rows * sizeof(int*);
64 matrix = malloc(rows_size);
65 if(matrix == NULL){
66 perror("malloc failled");
67 return 1;
68 }
69 size_t data_size = (size_t)m_rows * m_cols * sizeof(int);
70 int *data;
71 if(posix_memalign((void**)&data, 64, data_size) != 0){
72 perror("not able to alocate memory");
73 free(matrix);
74 return 1;
75 }
76 t_t1 = clock() - t_t1;
77 double t1_ttaken = ((double)t_t1)/CLOCKS_PER_SEC;
78 printf(" %f sec\n",t1_ttaken);
79
80 printf("2nd --> Populate the matrix\n");
81 clock_t t_t2; t_t2 = clock();
82 for(int r = 0; r<m_rows;r++){
83 matrix[r] = data + r * m_cols;
84 }
85 for(int r = 0; r < m_rows; r++){
86 for(int c = 0; c < m_cols; c++){
87 matrix[r][c] = r*m_cols+c;
88 }
89 }
90 t_t2 = clock() - t_t2;
91 double t2_ttaken = ((double)t_t2)/CLOCKS_PER_SEC;
92 printf(" %f sec\n",t2_ttaken);
93
94 printf("3rd --> Search matrix\n");
95 clock_t t_t3; t_t3 = clock();
96 int threads_to_use = 800;
97 run_parallel_search(threads_to_use);
98 t_t3 = clock() - t_t3;
99 double t3_ttaken = ((double)t_t3)/CLOCKS_PER_SEC;
100 printf(" %f sec\n",t3_ttaken);
101
102 printf("Done\n The biggest value found is %d", hv);
103 free(data);
104 free(matrix);
105 return 0;
106 }