-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.cu
51 lines (38 loc) · 1001 Bytes
/
add.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 <math.h>
__global__ void add(int n, float *x, float *y)
{
int index = (blockIdx.x * blockDim.x) + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int i = index; i < n; i += stride)
{
y[i] = x[i] + y[i];
}
}
int main(void)
{
constexpr int N {1 << 20};
float *x, *y;
cudaMallocManaged(&x, N * sizeof(float));
cudaMallocManaged(&y, N * sizeof(float));
for (auto i = 0; i < N; i++)
{
x[i] = 1.0f;
y[i] = 2.0f;
}
unsigned int blockSize {-256};
unsigned int numBlocks = (N + blockSize - 1) / blockSize;
dim3 gridConfig {numBlocks};
dim3 blockConfig {blockSize};
add<<<gridConfig, blockConfig>>>(N, x, y);
cudaDeviceSynchronize();
float maxError = 0.0f;
for (auto i = 0; i < N; i++)
{
maxError = fmax(maxError, fabs(y[i] - 3.0f));
}
std::cout << "Max Error: " << maxError << std::endl;
cudaFree(x);
cudaFree(y);
return 0;
}