forked from gpu-mode/lectures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coalesce.cu
51 lines (39 loc) · 1.33 KB
/
coalesce.cu
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
#include <iostream>
#include <cuda_runtime.h>
__global__ void copyDataNonCoalesced(float *in, float *out, int n) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < n) {
out[index] = in[(index * 2) % n];
}
}
__global__ void copyDataCoalesced(float *in, float *out, int n) {
int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < n) {
out[index] = in[index];
}
}
void initializeArray(float *arr, int n) {
for(int i = 0; i < n; ++i) {
arr[i] = static_cast<float>(i);
}
}
int main() {
const int n = 1 << 24; // Increase n to have a larger workload
float *in, *out;
cudaMallocManaged(&in, n * sizeof(float));
cudaMallocManaged(&out, n * sizeof(float));
initializeArray(in, n);
int blockSize = 128; // Define block size
// int blockSize = 1024; // change this when talking about occupancy
int numBlocks = (n + blockSize - 1) / blockSize; // Ensure there are enough blocks to cover all elements
// Launch non-coalesced kernel
copyDataNonCoalesced<<<numBlocks, blockSize>>>(in, out, n);
cudaDeviceSynchronize();
initializeArray(out, n); // Reset output array
// Launch coalesced kernel
copyDataCoalesced<<<numBlocks, blockSize>>>(in, out, n);
cudaDeviceSynchronize();
cudaFree(in);
cudaFree(out);
return 0;
}