gpt4 book ai didi

visual-c++ - 我如何使用 cudaMemcpy2D() DeviceToHost

转载 作者:行者123 更新时间:2023-12-02 22:03:35 24 4
gpt4 key购买 nike

我是 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");

这是输出。

Host main A Array 0 1 2 1 2 3 2 3 4

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

b array: 0 0 0 0 0 0 0 0 0

returned array 0 0 0 1.17549e-038 0 0 0 0 0

Press any key to continue . . .

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

如有任何帮助,我们将不胜感激。

最佳答案

如评论中所述,原始发布者为 cudaMemcpy2D 调用提供了不正确的参数。传输的宽度参数始终以字节为单位,因此在上面的代码中:

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

应该是

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

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

关于visual-c++ - 我如何使用 cudaMemcpy2D() DeviceToHost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16491232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com