1. 矩阵相乘再加 C = a*A*B + b*C
#include "cuda_runtime.h"
#include "cublas_v2.h"
#include <time.h>
#include <iostream>
using namespace std;
int const M = 6;
int const N = 10;
int main()
{
cublasStatus_t status;
//Host memory malloc
float *h_A = (float*)malloc(N*M*sizeof(float));
float *h_B = (float*)malloc(N*M*sizeof(float));
float *h_C = (float*)malloc(M*M*sizeof(float));
float *h_C_cpu = (float*)malloc(M*M*sizeof(float));
memset(h_C_cpu,0,M*M*sizeof(float));
//Initialize and print
for (int i=0; i<M*N; i++)
{
h_A[i] = (float)(rand()%10+1);
h_B[i] = (float)(rand()%10+1);
}
cout << "Matrix A is:" << endl;
for (int i=0; i<M*N; i++)
{
cout << h_A[i] << " ";
if ((i+1)%N == 0)
{
cout << endl;
}
}
cout << endl;
cout << "Matrix B is:" << endl;
for (int i=0; i<M*N; i++)
{
cout << h_B[i] << " ";
if ((i+1)%M == 0)
{
cout << endl;
}
}
cout << endl;
//CPU caculate
for(int i = 0; i<M; i++)
{
for(int j=0; j<M; j++)
{
for(int k=0; k<N; k++)
{
h_C_cpu[i*M+j] = h_C_cpu[i*M+j]+h_A[i*N+k]*h_B[k*M+j]*1 + 0;
}
}
}
cout << "The result from CPU is:" << endl;
for (int i=0; i<M*M; i++)
{
cout << h_C_cpu[i] << " ";
if ((i+1)%M == 0)
{
cout << endl;
}
}
cout << endl;
//Create handle;
cublasHandle_t handle;
status = cublasCreate(&handle);
if (status != CUBLAS_STATUS_SUCCESS)
{
if (status == CUBLAS_STATUS_NOT_INITIALIZED)
{
cout << "Fail to get an instance of blas object! Check whether you have free the handle!" << endl;
}
getchar();
return EXIT_FAILURE;
}
//Device memory malloc and initialize
float *d_A, *d_B, *d_C;
cudaMalloc((void**)&d_A, N*M*sizeof(float));
cudaMalloc((void**)&d_B, N*M*sizeof(float));
cudaMalloc((void**)&d_C, M*M*sizeof(float));
cublasSetVector(N*M, sizeof(float), h_A, 1, d_A, 1);
cublasSetVector(N*M, sizeof(float), h_B, 1, d_B, 1);
cudaThreadSynchronize();
//Call gpu operation
float a = 1;
float b = 0;
cons