c++ 推力问题:如何使用自定义排列顺序将host_vector复制到device_vector?

o2g1uqev  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(103)

我在主机中有一个阵列,我想将其传输到具有不同顺序的设备。
我试过这个玩具代码符合nvc++ test.cpp -stdpar

$ cat test.cpp
#include <iostream>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/copy.h>
#include <thrust/sequence.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <array>

using Real = float;

int main(int argc, char* argv[]) {

        std::array<std::size_t,6> idx{0,1,2,3,5,4};

        thrust::host_vector<Real> hvec(6);

        thrust::sequence(hvec.begin(),hvec.end());

        typedef thrust::host_vector<Real>::iterator EleItor;
        typedef std::array<std::size_t,6>::iterator IdxItor;

        thrust::permutation_iterator<EleItor,IdxItor> itor(hvec.begin(),idx.begin());

        thrust::device_vector<Real> test;
        thrust::copy(itor,itor+6,test);  // error
        thrust::copy(itor,itor+6,std::ostream_iterator<Real>(std::cout," ");  

}

问题是thrust::copy不允许从主机复制到设备,我如何绕过这个限制?

kqlmhetl

kqlmhetl1#

根据documentation,可以使用thrust::copy从主机复制到设备,但需要传递设备迭代器

//-----------------------------vvvvvvvv--
thrust::copy(itor, itor+6, test.begin());

注意,在此之前,您需要为设备向量分配内存。
幸运的是,thrust::device_vector有一个构造函数,其大小可以分配所需的内存。
您可以使用类似于以下内容的内容:

thrust::device_vector<Real> test(host_vector.size());

编辑(署名为@paleonix):
还有另一个构造函数可以使用迭代器,也就是说,可以在一行中同时执行分配和复制作为初始化,这也具有避免将内存不必要地初始化为0.0f的优点。

thrust::device_vector<Real> test(itor, itor+6);

相关问题