-
Notifications
You must be signed in to change notification settings - Fork 0
/
13b.cu
57 lines (42 loc) · 1.08 KB
/
13b.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
/* Compute the sum of two vectors using CUDA
* Vishwas S
*/
#include <stdio.h>
#include <stdlib.h>
__global__ void add(int *a, int *b, int *c, int n)
{
int id = blockIdx.x*blockDim.x + threadIdx.x;
if(id<n)
c[id] = a[id] + b[id];
}
int main()
{
int N;
int *a, *b, *c, *da, *db, *dc;
scanf("%d",&N);
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
a = (int *)calloc(N,sizeof(int));
b = (int *)calloc(N,sizeof(int));
c = (int *)calloc(N,sizeof(int));
for(int i = 0; i < N; i++)
{
a[i] = rand()%48;
b[i] = rand()%50;
}
int size = N*sizeof(int);
cudaMalloc(&da,size);
cudaMalloc(&db,size);
cudaMalloc(&dc,size);
cudaMemcpy(da,a,size,cudaMemcpyHostToDevice);
cudaMemcpy(db,b,size,cudaMemcpyHostToDevice);
cudaEventRecord(start);
add<<<(N+511)/512,512>>>(da,db,dc,N); //block count, threads per block
cudaEventRecord(stop);
cudaMemcpy(c,dc,size,cudaMemcpyDeviceToHost);
cudaEventSynchronize(stop);
float ms;
cudaEventElapsedTime(&ms,start,stop);
printf("%f\n",ms);
}