GPU矩阵计算

学习GPU加速 参考例子和网上博文写的GPU矩阵计算

//矩阵转置
__global__ void transposeGPU(double *outdata, double *indata, int width, int height)
{
    __shared__ double block[BLOCK_DIM][BLOCK_DIM + 1];
    unsigned int xIndex = blockIdx.x*BLOCK_DIM + threadIdx.x;
    unsigned int yIndex = blockIdx.y*BLOCK_DIM + threadIdx.y;

    if ((xIndex < width) && (yIndex < height))
    {
        unsigned int index_in = yIndex*width + xIndex;
        block[threadIdx.y][threadIdx.x] = indata[index_in];
    }

    __syncthreads();

    xIndex = blockIdx.y*BLOCK_DIM + threadIdx.x;
    yIndex = blockIdx.x*BLOCK_DIM + threadIdx.y;

    if ((xIndex < height) && (yIndex < width))
    {
        unsigned int index_out = yIndex*height + xIndex;
        outdata[index_out] = block[threadIdx.x][threadIdx.y];
        //        std::cout <<" !!index_out:" <<index_out<<" block[threadIdx.x][threadIdx.y]:"<< block[threadIdx.x][threadIdx.y] <<std::endl;
    }

}

void transpose(double *outdata, double *indata, int width, int height)
{
    double *d_a, *d_b;
    cudaMalloc((double**)&d_a, sizeof(double) * width * height);
    cudaMalloc((double**)&d_b, sizeof(double) * height * width);

    cudaMemcpy((void*)d_a, (void*)indata, sizeof(double) * width * height, cudaMemcpyHostToDevice);

    dim3 Threads(BLOCK_DIM, BLOCK_DIM);
    int b_x = ceil((float)width / (float)BLOCK_DIM);
    int b_y = ceil((float)height / (float)BLOCK_DIM);
    dim3 Blocks(b_x, b_y);

    transposeGPU << <Blocks, Threads >> > (d_b, d_a, width, height);
    cudaMemcpy((void*)outdata, (void*)d_b, sizeof(double) * width * height, cudaMemcpyDeviceToHost);

}
//矩阵乘法

template<int BLOCK_SIZE> __global__ void MatrixMulGPU(double *c, const double *a, const double *b, unsigned int WA, unsigned int WB)
{
    // Block index
    in

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值