gpt4 book ai didi

c++ - CUDA 推力 : copy from device to device

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:23 27 4
gpt4 key购买 nike

我使用标准 CUDA malloc 在 CUDA 中分配了一个内存数组,并将其传递给函数,如下所示:

void MyClass::run(uchar4 * input_data)

我还有一个类成员,它是一个推力 device_ptr 声明为:

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

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

现在,我想将输入数组复制到 thrust_device_ptr 中。我看过推力文档,其中很多都在谈论从设备复制到主机内存,反之亦然。我想知道在推力上执行此设备到设备复制的最佳性能最佳方式是什么,还是我应该只使用 cudaMemcpy?

最佳答案

执行此操作的规范方法是使用 thrust::copythrust::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

关于c++ - CUDA 推力 : copy from device to device,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29624011/

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