【问题标题】:How do I use cudaMemcpy2D() DeviceToHost如何使用 cudaMemcpy2D() DeviceToHost
【发布时间】:2019-07-28 05:14:54
【问题描述】:

我是 cuda 和 C++ 的新手,似乎无法弄清楚这一点。

我想要做的是将二维数组 A 复制到设备,然后将其复制回相同的数组 B。

我希望 B 数组与 A 具有相同的值,但有些地方我做错了。

CUDA - 4.2,编译为 win32,64 位机,NVIDIA Quadro K5000

这里是代码。

void main(){

cout<<"Host main" << endl;

// Host code
const int width = 3;
const int height = 3;
float* devPtr;
float a[width][height]; 

//load and display input array
cout << "a array: "<< endl;
for (int i = 0 ; i < width; i ++)
{
    for (int j = 0 ; j < height; j ++)
    {
        a[i][j] = i + j;
        cout << a[i][j] << " ";

    }
    cout << endl;
}
cout<< endl;


//Allocating Device memory for 2D array using pitch
size_t host_orig_pitch = width * sizeof(float); //host original array pitch in bytes
size_t pitch;// pitch for the device array 

cudaMallocPitch(&devPtr, &pitch, width * sizeof(float), height);

cout << "host_orig_pitch: " << host_orig_pitch << endl;
cout << "sizeof(float): " << sizeof(float)<< endl;
cout << "width: " << width << endl;
cout << "height: " << height << endl;
cout << "pitch:  " << pitch << endl;
cout << endl;

cudaMemcpy2D(devPtr, pitch, a, host_orig_pitch, width, height, cudaMemcpyHostToDevice);

float b[width][height];
//load b and display array
cout << "b array: "<< endl;
for (int i = 0 ; i < width; i ++)
{
    for (int j = 0 ; j < height; j ++)
    {
        b[i][j] = 0;
        cout << b[i][j] << " ";
    }
    cout << endl;
}
cout<< endl;


//MyKernel<<<100, 512>>>(devPtr, pitch, width, height);
//cudaThreadSynchronize();


//cudaMemcpy2d(dst, dPitch,src ,sPitch, width, height, typeOfCopy )
cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width, height, cudaMemcpyDeviceToHost);


// should be filled in with the values of array a.
cout << "returned array" << endl;
for(int i = 0 ; i < width ; i++){
    for (int j = 0 ; j < height ; j++){
        cout<< b[i][j] << " " ;
    }
    cout<<endl;
}

cout<<endl;
system("pause");

}

这是输出。

主机主A阵列0 1 2 1 2 3 2 3 4

host_orig_pitch: 12 sizeof(float): 4 width: 3 height: 3 pitch: 512

b数组:0 0 0 0 0 0 0 0 0

返回数组 0 0 0 1.17549e-038 0 0 0 0 0

按任意键继续。 . .

如果需要更多信息,请告诉我,我会发布。

任何帮助将不胜感激。

【问题讨论】:

  • cudaMemcpy2D中,第5个参数也是字节,所以应该是width * sizeof(float)而不是width
  • 太棒了!谢谢你。做到了。 :)

标签: visual-c++ cuda


【解决方案1】:

如 cmets 中所述,原始发帖人为 cudaMemcpy2Dcall 提供了不正确的参数。传输的宽度参数总是以字节为单位,所以在上面的代码中:

cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width, height, cudaMemcpyDeviceToHost);

应该是

cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width * sizeof(float), height, cudaMemcpyDeviceToHost);

请注意,此答案已作为社区 wiki 添加,以将此问题从未回答列表中删除

【讨论】:

  • @WouterJ:谢谢。我怀疑使用平板电脑的危险。看到你已经注意到了,你可以投票吗?然后它就永远不在未答复的列表中了。
  • 我认为最好将其关闭为“offtopic > 一个简单的错字”原因
  • @WouterJ:我试图关闭这样的问题,但关闭投票不可避免地会在关闭之前过期。这是解决方案#2
猜你喜欢
  • 2019-10-15
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 2019-08-23
  • 2020-05-06
相关资源
最近更新 更多