-
Notifications
You must be signed in to change notification settings - Fork 2
/
pi.c
107 lines (74 loc) · 2.19 KB
/
pi.c
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
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <hiprand/hiprand.h>
float cpu_pi(int n)
{
int inside, i;
float *x, *y;
x = (float *)malloc(n * sizeof(float));
y = (float *)malloc(n * sizeof(float));
for (i = 0; i < n; i++) {
x[i] = (float)rand() / (float)RAND_MAX;
y[i] = (float)rand() / (float)RAND_MAX;
}
inside = 0;
for (i = 0; i < n; i++) {
if (x[i]*x[i] + y[i]*y[i] < 1.0) {
inside++;
}
}
free(x);
free(y);
return 4.0 * (float)inside / (float)n;
}
float gpu_pi(size_t n)
{
hiprandGenerator_t g;
int istat;
int inside;
float *x, *y, pi;
pi = 0;
x = (float *)malloc(n * sizeof(float));
y = (float *)malloc(n * sizeof(float));
// TODO start: allocate x and y in the device with OpenMP enter data
// TODO end
inside = 0;
istat = hiprandCreateGenerator(&g, HIPRAND_RNG_PSEUDO_DEFAULT);
// TODO start: use device pointer for HIP random generator calls
istat = hiprandGenerateUniform(g, x, n);
if (istat != HIPRAND_STATUS_SUCCESS) printf("Error in hiprandGenerate: %d\n", istat);
istat = hiprandGenerateUniform(g, y, n);
if (istat != HIPRAND_STATUS_SUCCESS) printf("Error in hiprandGenerate: %d\n", istat);
// TODO end
// TODO start: execute the loop in parallel in device
for (int i = 0; i < n; i++) {
if (x[i]*x[i] + y[i]*y[i] < 1.0) {
inside++;
}
}
// TODO end
// TODO start: deallocate x and y in the device with OpenMP exit data
// TODO end
free(x);
free(y);
istat = hiprandDestroyGenerator(g);
if (istat != HIPRAND_STATUS_SUCCESS) {
fprintf(stderr, "Error in hiprandDestroyGenerator: %d\n", istat);
}
pi = 4.0 * (float)inside / (float)n;
return pi;
}
int main(int argc, char *argv[])
{
int nsamples;
if (argc < 2) {
fprintf(stderr, "Usage: %s N\n where N is the number samples\n", argv[0]);
exit(EXIT_FAILURE);
} else {
nsamples = atoi(argv[1]);
}
printf("Pi equals to %9.6f\n", cpu_pi(nsamples));
printf("Pi equals to %9.6f\n", gpu_pi(nsamples));
return 0;
}