这是这里提供从没有答案的列表中删除这个问题非常晚的答案。我确信OP已经找到了解决方案(自2012年5月以来:-)),但我相信以下内容可能对其他用户有用。
正如@talonmies指出的那样,问题可以通过融合聚集减少来解决。该解决方案确实是Thurst的permutation_iterator
和reduce
的应用。 permutation_iterator
允许(隐含地)根据indices
数组中的索引对目标数组x
重新排序。 reduce
执行(隐式)重新排序的数组的总和。
本申请是Thrust's documentation一部分,下面报道了方便
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/reduce.h>
#include <thrust/device_vector.h>
// this example fuses a gather operation with a reduction for
// greater efficiency than separate gather() and reduce() calls
int main(void)
{
// gather locations
thrust::device_vector<int> map(4);
map[0] = 3;
map[1] = 1;
map[2] = 0;
map[3] = 5;
// array to gather from
thrust::device_vector<int> source(6);
source[0] = 10;
source[1] = 20;
source[2] = 30;
source[3] = 40;
source[4] = 50;
source[5] = 60;
// fuse gather with reduction:
// sum = source[map[0]] + source[map[1]] + ...
int sum = thrust::reduce(thrust::make_permutation_iterator(source.begin(), map.begin()),
thrust::make_permutation_iterator(source.begin(), map.end()));
// print sum
std::cout << "sum is " << sum << std::endl;
return 0;
}
在上述例子中,map
起着indices
作用,同时source
起着x
的作用。
关于在您的评论的另一个问题(迭代项的数目减少),如果你想重复这将足以以下行
int sum = thrust::reduce(thrust::make_permutation_iterator(source.begin(), map.begin()),
thrust::make_permutation_iterator(source.begin(), map.end()));
改变
int sum = thrust::reduce(thrust::make_permutation_iterator(source.begin(), map.begin()),
thrust::make_permutation_iterator(source.begin(), map.begin()+N));
仅在索引数组map
的第一个N
条款。
最后,关于从主机使用global_array
的可能性,您应该注意到这是一个驻留在设备上的矢量,所以您首先需要将其移动到主机上。
你能解释一下你想做什么吗?总和是一个总数(即你的'支持'功能是否应该是融合聚集 - 减少)还是其他的?你是否有某些理由选择将'support'作为设备函数来显示,或者是基本上不相关的? – talonmies
如果你使用Thrust,你应该用适当的C++风格,IMO编码。 – leftaroundabout
@talonmies你解决了我的问题,只是说“融合缩减”!这正是我期待的!但有几件事情:从* Thrust快速入门指南*(permutation_iterator)中的例子来看,它们只是迭代整体数组。而不是它,我想迭代一定数量(如上面的for循环);我怎样才能做到这一点 ?而且,我应该从设备上复制global_array [N]吗? – davideberdin