CUDA thrust:从设备复制到设备

5

我有一个使用标准CUDA malloc分配的内存数组,并将其传递给以下函数:

void MyClass::run(uchar4 * input_data)

我还有一个类成员是一个thrust device_ptr,声明如下:

thrust::device_ptr<uchar4> data = thrust::device_malloc<uchar4(num_pts);

这里的num_pts是数组中值的数量,input_data指针保证长度为num_pts。

现在,我想将输入数组复制到thrust_device_ptr中。我查看了thrust文档,并且其中很多内容都涉及从设备到主机内存和相反方向的复制。我想知道在thrust上执行设备到设备复制的最佳性能优化方法是什么,或者我应该只使用cudaMemcpy?


1
是的,你可以使用cudaMemcpy函数,并设置cudaMemcpyDeviceToDevice标志,首先需要从thrust::device_ptr中提取原始指针,像这样:uchar4* data_ptr = thrust::raw_pointer_cast(data); - sgarizvi
1个回答

3

最常规的方法是使用thrust::copy函数。 thrust::device_ptr具有标准指针语义,API会自动识别源指针和目标指针是否在主机或设备上,示例如下:

#include <thrust/device_malloc.h>
#include <thrust/device_ptr.h>
#include <thrust/copy.h>
#include <iostream>

int main()
{
    // Initial host data
    int ivals[4] = { 1, 3, 6, 10 };

    // Allocate and copy to first device allocation
    thrust::device_ptr<int> dp1 = thrust::device_malloc<int>(4);
    thrust::copy(&ivals[0], &ivals[0]+4, dp1);

    // Allocate and copy to second device allocation
    thrust::device_ptr<int> dp2 = thrust::device_malloc<int>(4);
    thrust::copy(dp1, dp1+4, dp2);

    // Copy back to host
    int ovals[4] = {-1, -1, -1, -1};
    thrust::copy(dp2, dp2+4, &ovals[0]);

    for(int i=0; i<4; i++)
        std::cout << ovals[i] << std::endl;


    return 0;
}

它的功能是:

talonmies@box:~$ nvcc -arch=sm_30 thrust_dtod.cu 
talonmies@box:~$ ./a.out 
1
3
6
10

1
这让我找到了正确的方法!最终我使用了推力向量,但通过device_ptr包装原始输入指针,然后使用copy解决了问题! - Luca
您好,我尝试直接声明设备向量,但复制函数无法正常工作。 - ztdep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接