[英]A thrust problem: How can I copy a host_vector to device_vector with a customized permutation order?
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我在主机中有一个数组,我想以不同的顺序将它传输到设备。
我试过这个玩具代码符合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
不允许从主机复制到设备,我怎样才能绕过这个限制?
根据文档,可以使用thrust::copy
从主机复制到设备,但您需要传递设备迭代器:
//-----------------------------vvvvvvvv--
thrust::copy(itor, itor+6, test.begin());
请注意,在此之前,您需要为设备向量分配 memory。
幸运的是, thrust::device_vector
有一个构造函数,其大小将分配所需的 memory。
你可以使用类似的东西:
thrust::device_vector<Real> test(host_vector.size());
编辑(归功于@paleonix):
还有另一个采用迭代器的构造函数,即可以在一行中同时进行分配和复制作为初始化,这也具有避免将 memory 不必要地初始化为0.0f
的优点。
thrust::device_vector<Real> test(itor, itor+6);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.