cudaMallocPitch()使用

名称 cudaMallocPitch – 向GPU分配存储器

概要 cudaError_t cudaMallocPitch( void** devPtr,size_t* pitch,size_t widthInBytes,size_t height )

说明 向设备分配至少widthInBytes*height字节的线性存储器,并以*devPtr的形式返回指向所分配存储器的指针。该函数可以填充所分配的存储器,以确保在地址从一行更新到另一行时,给定行的对应指针依然满足对齐要求。cudaMallocPitch()以*pitch的形式返回间距,即所分配存储器的宽度,以字节为单位。间距用作存储器分配的一个独立参数,用于在2D数组内计算地址。如果给定一个T类型数组元素的行和列,可按如下方法计算地址:

T* pElement = (T*)((char*)BaseAddress + Row * pitch) + Column;

对于2D数组的分配,建议程序员考虑使用cudaMallocPitch()来执行间距分配。由于硬件中存在间距对齐限制,如果应用程序将在设备存储器的不同区域之间执行2D存储器复制(无论是线性存储器还是CUDA数组),这种方法将非常有用。


例子:为EmuDebug 
原来《CUDA编程指南》上给出的pitch的类型为int,在实际运行时与cudaMallocPitch()类型不匹配。

/************************************************************************/
/*  This is a example of the CUDA program. 
/************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <cutil.h>

/************************************************************************/ 
/* myKernel                                                           */ 
/************************************************************************/ 
__global__ void myKernel(float* devPtr,int height,int width,int pitch) 

    for(int r=0;r    { 
        float* row=(float*)((char*)devPtr+r*pitch); 
        for (int c=0;c        { 
            float element=row[c]; 
            printf("%f/n",element);//模拟运行 
        } 
    } 
}

/************************************************************************/ 
/* Main CUDA                                                            */ 
/************************************************************************/ 
int main(int argc, char* argv[]) 

    size_t width=10; 
    size_t height=10; 

    float* decPtr; 
   //pitch的值应该为size_t在整形的时,与函数参数不匹配 
    size_t pitch; 
    cudaMallocPitch((void**)&decPtr,&pitch,width*sizeof(float),height);  
    myKernel<<<1,1>>>(decPtr,10,10,pitch); 
    cudaFree(decPtr);

    printf("%d/n",pitch);

    //CUT_EXIT(argc, argv);

    return 0; 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值