CUDA-矩阵运算

9 篇文章 0 订阅

这里对矩阵运算做个记录

 

头文件

头文件

#include "cuda_runtime.h"
#include "cublas_v2.h"

辅助函数

//两个模板函数
#define fatalError(s) do {                                             \
    std::stringstream _where, _message;                                \
    _where << __FILE__ << ':' << __LINE__;                             \
    _message << std::string(s) + "\n" << __FILE__ << ':' << __LINE__;  \
    std::cerr << _message.str() << "\nAborting...\n";                  \
    cudaDeviceReset();                                                 \
    exit(1);                                                           \
} while(0)

#define callCuda(status) do {                                  		   \
    std::stringstream _error;                                          \
    if (status != 0) {                                                 \
    	_error << "Cuda failure: " << status;                          \
    	fatalError(_error.str());                                      \
    }                                                                  \
} while(0)


//矩阵
void printMatrix(int *x, int n, int r, int c, std::string name) {
	printf("%s: \n", name.c_str());
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++)
			printf("%d, \t", x[i + j * r]);
		printf("\n");
	}
	printf("\n");
}

//随机数据生成
void generateVector(float *v, int n, int lower, int upper) {
	for (int i = 0; i < n; i++)
		v[i] = (float)(rand() % (upper - lower) + lower);
}

使用矩阵相乘函数

__host__ void cudaDDotTest2()
{

	printf("---- Demo ans := x .* y ----\n");
	cudaError_t cudaStat;
	cublasStatus_t stat;
	cublasHandle_t handle;
	const int n = 25;
	float *x = new float[n];
	generateVector(x, n);
	printVector(x, n, "x");
	printMatrix(x,25,5,5,"matrixX");
	float *y = new float[n];
	generateVector(y, n);
	printVector(y, n, "y");
	printMatrix(y, 25, 5, 5, "matriY");
	float *d_x;
	float *d_y;
	cudaStat = cudaMalloc((void**)&d_x, n * sizeof(*x));
	cudaStat = cudaMalloc((void**)&d_y, n * sizeof(*y));
	stat = cublasCreate(&handle);
	stat = cublasSetVector(n, sizeof(*x), x, 1, d_x, 1);
	stat = cublasSetVector(n, sizeof(*y), y, 1, d_y, 1);
	float result;
	stat = cublasSdot(handle, n, d_x, 1, d_y, 1, &result);
	printNumber(&result, "ans");
	cudaFree(d_x);
	cudaFree(d_y);
	cublasDestroy(handle);
	delete[] x;
	delete[] y;
}

测试,这里生成5*5矩阵,进行GPU求和

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值