【发布时间】: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