使用CUBLAS的一些小例子

本文通过一个实例展示了如何使用CUBLAS库进行矩阵相乘并加上常数项的操作,即C = a*A*B + b*C。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值