-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_multiply.cu
More file actions
77 lines (69 loc) · 1.54 KB
/
matrix_multiply.cu
File metadata and controls
77 lines (69 loc) · 1.54 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
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<bits/stdc++.h>
#include<cuda.h>
using namespace std;
#define CEIL(a, b) ((a-1)/b +1)
__global__ void Multiply(int* d_a,int* d_b,int* d_c, int N)
{
int x=blockIdx.x*blockDim.x + threadIdx.x;
int y=blockIdx.y*blockDim.y + threadIdx.y;
int index=x*N+y;
if(x<N && y<N)
{
int res=0;
for(int i=0;i<N;i++)
res += (d_a[x*N+i] * d_b[i*N+y]);
d_c[index]=res;
}
}
int main()
{
int N;
cout<<"enter size : ";
cin>>N;
int h_a[N][N], h_b[N][N], h_c[N][N], h_d[N][N];
int bytes=N*N*sizeof(int);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
h_a[i][j]= rand()%10 ;
h_b[i][j]= rand()%10 ;
}
}
int *d_a, *d_b, *d_c;
cudaMalloc((void**)&d_b, bytes);
cudaMalloc((void**)&d_a, bytes);
cudaMalloc((void**)&d_c, bytes);
cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice);
cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice);
dim3 block(32, 32, 1);
dim3 grid(CEIL(N, 32), CEIL(N, 32), 1);
Multiply<<<grid, block>>>(d_a,d_b,d_c,N);
cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
int res=0;
for(int k=0;k<N;k++)
res += (h_a[i][k]*h_b[k][j]);
h_d[i][j]=res;
}
}
bool verify=true;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(h_c[i][j]!=h_d[i][j])
verify=false;
}
}
if(verify)
cout<<"Result is Correct";
else
cout<<"Incorrect Result";
cudaFree(d_a);
cudaFree(d_b);
cudaFree(d_c);
}