有没有更好更快的方法使用推力从 CPU 内存复制到 GPU? [英] is there a better and a faster way to copy from CPU memory to GPU using thrust?

查看:21
本文介绍了有没有更好更快的方法使用推力从 CPU 内存复制到 GPU?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在使用推力.我注意到,为了使用推力,必须始终将数据从 cpu 内存复制到 gpu 内存.
让我们看看下面的例子:

Recently I have been using thrust a lot. I have noticed that in order to use thrust, one must always copy the data from the cpu memory to the gpu memory.
Let's see the following example :

int foo(int *foo)
{
     host_vector<int> m(foo, foo+ 100000);
     device_vector<int> s = m;
}

我不太确定 host_vector 构造函数是如何工作的,但似乎我正在复制初始数据,来自 *foo,两次 - 一次初始化时的 host_vector,以及初始化 device_vector 时的另一个时间.有没有更好的方法从 cpu 复制到 gpu 而无需制作中间数据副本?我知道我可以使用 device_ptr 作为包装器,但这仍然不能解决我的问题.
谢谢!

I'm not quite sure how the host_vector constructor works, but it seems like I'm copying the initial data, coming from *foo, twice - once to the host_vector when it is initialized, and another time when device_vector is initialized. Is there a better way of copying from cpu to gpu without making an intermediate data copies? I know I can use device_ptras a wrapper, but that still doesn't fix my problem.
thanks!

推荐答案

device_vector 的一个构造函数采用由两个迭代器指定的一系列元素.理解示例中的原始指针足够聪明,因此您可以直接构造 device_vector 并避免临时 host_vector:

One of device_vector's constructors takes a range of elements specified by two iterators. It's smart enough to understand the raw pointer in your example, so you can construct a device_vector directly and avoid the temporary host_vector:

void my_function_taking_host_ptr(int *raw_ptr, size_t n)
{
  // device_vector assumes raw_ptrs point to system memory
  thrust::device_vector<int> vec(raw_ptr, raw_ptr + n);

  ...
}

如果您的原始指针指向 CUDA 内存,请引入 device_ptr:

If your raw pointer points to CUDA memory, introduce a device_ptr:

void my_function_taking_cuda_ptr(int *raw_ptr, size_t n)
{
  // wrap raw_ptr before passing to device_vector
  thrust::device_ptr<int> d_ptr(raw_ptr);

  thrust::device_vector<int> vec(d_ptr, d_ptr + n);

  ...
}

使用 device_ptr 不会分配任何存储空间;它只是对类型系统中指针的位置进行编码.

Using a device_ptr doesn't allocate any storage; it just encodes the location of the pointer in the type system.

这篇关于有没有更好更快的方法使用推力从 CPU 内存复制到 GPU?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆