-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector Addition 4A.txt
56 lines (44 loc) · 1.25 KB
/
Vector Addition 4A.txt
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
#include <stdio.h>
#include <stdlib.h>
#define N 1000000
__global__ void add(int *a, int *b, int *c) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if (tid < N) {
c[tid] = a[tid] + b[tid];
}
}
int main() {
int *a, *b, *c;
int *d_a, *d_b, *d_c;
int size = N * sizeof(int);
// Allocate memory on host
a = (int*)malloc(size);
b = (int*)malloc(size);
c = (int*)malloc(size);
// Initialize arrays
for (int i = 0; i < N; i++) {
a[i] = i;
b[i] = i * 2;
}
// Allocate memory on device
cudaMalloc(&d_a, size);
cudaMalloc(&d_b, size);
cudaMalloc(&d_c, size);
// Copy data from host to device
cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
// Launch kernel with 1 million threads
add<<<(N + 255) / 256, 256>>>(d_a, d_b, d_c);
// Copy result from device to host
cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
// Print first and last elements of result
printf("c[0] = %d, c[%d] = %d\n", c[0], N-1, c[N-1]);
// Free memory
free(a);
free(b);
free(c);
cudaFree(d_a);
cudaFree(d_b);
cudaFree(d_c);
return 0;
}