-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenmp.c
More file actions
148 lines (121 loc) · 2.59 KB
/
openmp.c
File metadata and controls
148 lines (121 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// g++ -fopenmp openmp.c -o openmp.out -O3 && ./openmp.out 10 100
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <time.h>
#include <omp.h>
#include "config.h"
#include <string.h>
void showDistances(int matrix[], int n);
void populateMatrix(int *matrix, int n, int density);
void floydWarshall(int* matrix, uint n, int threads);
int main(int argc, char** argv)
{
uint n, density, threads;
if(argc <= 3)
{
n = DEFAULT;
density = 100;
threads = omp_get_max_threads();
}
else
{
n = atoi(argv[1]);
density = atoi(argv[2]);
threads = atoi(argv[3]);
}
int* matrix;
matrix = (int*) malloc(n * n * sizeof(int));
populateMatrix(matrix, n, density);
printf("*** Adjacency matrix:\n");
showDistances(matrix, n);
struct timespec start, end;
long long accum;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
floydWarshall(matrix, n, threads);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
accum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
printf("*** The solution is:\n");
showDistances(matrix, n);
printf("[SEQUENTIAL] Total elapsed time %lld ns\n", accum);
free(matrix);
return 0;
}
void floydWarshall(int* matrix, uint n, int threads)
{
int i, j, k;
int *rowK = (int*)malloc(sizeof(int)*n);
#pragma omp parallel num_threads(threads) private(k) shared(matrix, rowK)
for (k = 0; k < n; k++)
{
#pragma omp master
memcpy(rowK, matrix + (k * n), sizeof(int)*n);
#pragma omp for private(i, j) schedule(static)
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
int newPath = matrix[i * n + k] + rowK[j];
if (matrix[i * n + j] > newPath)
{
matrix[i * n + j] = newPath;
}
}
}
}
}
void showDistances(int matrix[], int n)
{
if(PRINTABLE)
{
int i, j;
printf(" ");
for(i = 0; i < n; i++)
{
printf("[%d] ", i);
}
printf("\n");
for(i = 0; i < n; i++) {
printf("[%d]", i);
for(j = 0; j < n; j++)
{
if(matrix[i * n + j] == INF)
{
printf(" inf");
}
else
{
printf("%5d", matrix[i * n + j]);
}
}
printf("\n");
}
printf("\n");
}
}
void populateMatrix(int *matrix, int n, int density)
{
uint i, j, value;
srand(42);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++){
if(i == j)
{
matrix[i*n+j] = 0;
}
else
{
value = 1 + rand() % MAX;
if(value > density)
{
matrix[i*n+j] = INF;
}
else
{
matrix[i*n+j] = value;
}
}
}
}
}