如何确定cuda程序的block数量和线程数量

第一步获取GPU硬件有多少block,有多少线程,代码如下

int getThreadNum()
{
    cudaDeviceProp prop;
    int count;

    HANDLE_ERROR(cudaGetDeviceCount(&count));
    printf("gpu num %d\n", count);
    HANDLE_ERROR(cudaGetDeviceProperties(&prop, 0));
    printf("max thread num: %d\n", prop.maxThreadsPerBlock);
    printf("max grid dimensions: %d, %d, %d)\n",
     prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
    return prop.maxThreadsPerBlock;
}

我的机器block数量为(2147483647,65535,65535),每个block线程数量为1024

第二步根据实际矩阵大小看需要多少block

例如有一个 1920×1080的一维矩阵,应该如何设计blockNum和ThreadNum ?

int threadNum = getThreadNum();
int blockNum = (width * height - 0.5) / threadNum + 1;

我的机器block数量非常多,所以用1维就够了,ThreadNum用机器最大的线程1024即可,那么blockNum就等于总数除以每个block的线程数,为什么要 -0.5和+1是为了防止整除、进一位等,总之加上为好

第三步开始使用

conv<<<blockNum, threadNum>> >
        (imgGpu, kernelGpu, resultGpu, width, height, kernelSize);
__global__ void conv(float *img, float *kernel, float *result, 
    int width, int height, int kernelSize)
    {
        int ti = threadIdx.x;
        int bi = blockIdx.x;
        int id = (bi * blockDim.x + ti);
        if(id >= width * height)
        {
            return;
        }
        int row = id / width;
        int col = id % width;
        for(int i = 0; i < kernelSize; ++i)
        {
            for(int j = 0; j < kernelSize; ++j)
            {
                float imgValue = 0;
                int curRow = row - kernelSize / 2 + i;
                int curCol = col - kernelSize / 2 + j;
                if(curRow < 0 || curCol < 0 || curRow >= height || curCol >= width)
                {}
                else
                {
                    imgValue = img[curRow * width + curCol];
                }
                result[id] += kernel[i * kernelSize + j] * imgValue;
            }

        }
    }

 

 

  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值