-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhipMallocManagedVecAdd.cpp
More file actions
67 lines (52 loc) · 1.63 KB
/
hipMallocManagedVecAdd.cpp
File metadata and controls
67 lines (52 loc) · 1.63 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
#include <hip/hip_runtime.h>
#define HIP_ASSERT(x) (assert((x) == hipSuccess))
#define N 100000000
__global__ void vector_add(float *c, float *a, float *b, int n) {
int tid = blockDim.x * blockIdx.x + threadIdx.x;
if (tid < N) {
c[tid] = a[tid] + b[tid];
}
}
int main() {
float *a, *b, *c;
// Allocate managed memory
HIP_ASSERT(hipMallocManaged(&a, sizeof(float) * N));
HIP_ASSERT(hipMallocManaged(&b, sizeof(float) * N));
HIP_ASSERT(hipMallocManaged(&c, sizeof(float) * N));
// Initialize host arrays
for (int i = 0; i < N; i++) {
a[i] = 1.0f;
b[i] = 2.0f;
}
float gpu_elapsed_time_ms, cpu_elapsed_time_ms;
// Some events to count the execution time
hipEvent_t start, stop;
HIP_ASSERT(hipEventCreate(&start));
HIP_ASSERT(hipEventCreate(&stop));
int blockSize = 256;
int gridSize = (N + blockSize - 1) / blockSize;
// Start to count execution time of GPU version
HIP_ASSERT(hipEventRecord(start, 0));
// Executing kernel
vector_add<<<gridSize, blockSize>>>(c, a, b, N);
// Time counting terminate
HIP_ASSERT(hipEventRecord(stop, 0));
HIP_ASSERT(hipDeviceSynchronize());
HIP_ASSERT(hipEventSynchronize(stop));
// Compute time elapse on GPU computing
HIP_ASSERT(hipEventElapsedTime(&gpu_elapsed_time_ms, start, stop));
printf("Time elapsed on vector addition on GPU: %f ms.\n\n",
gpu_elapsed_time_ms);
// Validation
// for (int i = 0; i < N; i++) {
// if (c[i] != a[i] + b[i]) {
// printf("Validation failed at element %d!\n", i);
// exit(-1);
// }
// }
// Deallocate device memory
hipFree(a);
hipFree(b);
hipFree(c);
return 0;
}