-
Notifications
You must be signed in to change notification settings - Fork 0
/
intAdd.cu
71 lines (53 loc) · 1.28 KB
/
intAdd.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cuda_runtime.h>
using namespace std;
__global__ void vecAddition(int *d_a, int *d_b, int *d_c, int n)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
if (i < n)
{
d_c[i] = d_a[i] + d_b[i];
}
}
void printArray(int *h_num, int n)
{
for (size_t i = 0; i < n; i++)
{
cout << h_num[i] << endl;
}
}
int main()
{
// create two array
int n = 10;
int size = sizeof(int) * n;
int *h_a = (int *)malloc(size);
int *h_b = (int *)malloc(size);
int *h_c = (int *)malloc(size);
for (size_t i = 0; i < n; i++)
{
h_a[i] = static_cast<int>(i);
h_b[i] = static_cast<int>(i * 2);
}
// printArray(h_a, n);
// printArray(h_b, n);
// allocate cuda memory
int *d_a;
int *d_b;
int *d_c;
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size);
cudaMemcpy(d_a, h_a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, h_b, size, cudaMemcpyHostToDevice);
vecAddition<<<ceil(n/256.0), 256>>>(d_a, d_b, d_c, n);
cudaMemcpy(h_c, d_c, size, cudaMemcpyDeviceToHost);
printArray(h_c, n);
cudaFree(d_a);
cudaFree(d_b);
cudaFree(d_c);
free(h_a);
free(h_b);
free(h_c);
return 0;
}