-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectorAdd.cu
More file actions
54 lines (40 loc) · 1.17 KB
/
vectorAdd.cu
File metadata and controls
54 lines (40 loc) · 1.17 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
#include<stdio.h>
#include<cuda_runtime.h>
__global__ void vectorAdd(int *A, int* B, int* C, int n) {
int i = threadIdx.x + blockDim.x * blockIdx.x;
if(i < n) {
C[i] = A[i] + B[i];
}
}
int main(int argc, char **argv) {
int *A, *B, *C;
int *d_A, *d_B, *d_C;
long long SIZE = 1024LL * 1024 * 32;
long size = SIZE * sizeof(int);
A = (int*) malloc(size);
B = (int*) malloc(size);
C = (int*)malloc(size);
cudaMalloc((void**)&d_A, size);
cudaMalloc((void**)&d_B, size);
cudaMalloc((void**)&d_C, size);
int threadsPerBlock = atoi(argv[1]);
for(int i = 0; i < SIZE; ++i) {
A[i] = i;
B[i] = SIZE-i;
}
int blocksPerGrid = (SIZE + threadsPerBlock - 1) / threadsPerBlock;
cudaMemcpy(d_A, A, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_B, B, size, cudaMemcpyHostToDevice);
vectorAdd<<<blocksPerGrid, threadsPerBlock>>> (d_A, d_B, d_C, SIZE);
cudaMemcpy(C, d_C, size, cudaMemcpyDeviceToHost);
for(int i = 0; i < SIZE; ++i) {
printf("%d %d %d\n", A[i], B[i], C[i]);
}
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
free(A);
free(B);
free(C);
return 0;
}