cudaMallocPitch()

名称 cudaMallocPitch – 向GPU分配存储器

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

说明 向设备分配至少widthInBytesheight字节的线性存储器,并以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;

}
————————————————
版权声明:本文为CSDN博主「something的马甲」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jdhanhua/article/details/4813725

猜你喜欢

转载自blog.csdn.net/weixin_45590043/article/details/123673766