-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathproject_005 Vector Addition
More file actions
67 lines (46 loc) · 1.53 KB
/
Copy pathproject_005 Vector Addition
File metadata and controls
67 lines (46 loc) · 1.53 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
55
56
57
58
59
60
61
62
63
64
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <cuda.h>
#define SIZE 1024*216
__global__ void add(int* a, int* b, int* c, int N) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
c[index] = a[index] + b[index];
printf("\nHello ");
}
// Function to populate a vector with random integers
void random_ints(int* x, int size) {
for (int i = 0; i < size; i++) {
x[i] = rand() % 100;
}
}
int main(void) {
int* a, * b, * c; // host copies of a, b, c
int* d_a, * d_b, * d_c; // device copies of a, b, c
int size = SIZE * sizeof(int);
// Allocate space for device copies of a, b, c
cudaMalloc((void**)&d_a, size);
cudaMalloc((void**)&d_b, size);
cudaMalloc((void**)&d_c, size);
// Allocate space for host copies of a, b, c and setup input values
a = (int*)malloc(size); random_ints(a, SIZE);
b = (int*)malloc(size); random_ints(b, SIZE);
c = (int*)malloc(size);
// Copy inputs to device
cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
// Create events for timing
add << <216, 1024 >> > (d_a, d_b, d_c, SIZE);
// cudaDeviceSynchronize();
// Copy result back to host
cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
int i = 0;
for(i=0;i<SIZE;i++)
{
printf("\nElement ID = %d ---> %d + %d = %d",i, a[i], b[i], c[i]);
}
// Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
free(a); free(b); free(c);
return 0;
}