2012-05-04 19 views
2

我想总结一个数组使用Thrust库索引的数组的元素,但是我不能' t找到一个例子。换句话说,我想实现Matlab的语法Thrust:求和由另一个数组索引的数组的元素[Matlab的语法总和(x(indices))]

sum(x(indices)) 

这里是一个指导代码想指出我喜欢什么来实现:

#define N 65536 

// device array copied using cudaMemcpyToSymbol 
__device__ int global_array[N]; 

// function to implement with thrust 
__device__ int support(unsigned short* _memory, unsigned short* _memShort) 
{ 
    int support = 0; 

    for(int i=0; i < _memSizeShort; i++) 
     support += global_array[_memory[i]]; 

    return support;  
} 

此外,从主机代码,我可以使用global_array [N]没有复制回cudaMemcpyFromSymbol

每一个评论/答案是赞赏:)

感谢

+2

你能解释一下你想做什么吗?总和是一个总数(即你的'支持'功能是否应该是融合聚集 - 减少)还是其他的?你是否有某些理由选择将'support'作为设备函数来显示,或者是基本上不相关的? – talonmies

+0

如果你使用Thrust,你应该用适当的C++风格,IMO编码。 – leftaroundabout

+0

@talonmies你解决了我的问题,只是说“融合缩减”!这正是我期待的!但有几件事情:从* Thrust快速入门指南*(permutation_iterator)中的例子来看,它们只是迭代整体数组。而不是它,我想迭代一定数量(如上面的for循环);我怎样才能做到这一点 ?而且,我应该从设备上复制global_array [N]吗? – davideberdin

回答

1

这是这里提供从没有答案的列表中删除这个问题非常晚的答案。我确信OP已经找到了解决方案(自2012年5月以来:-)),但我相信以下内容可能对其他用户有用。

正如@talonmies指出的那样,问题可以通过融合聚集减少来解决。该解决方案确实是Thurst的permutation_iteratorreduce的应用。 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的可能性,您应该注意到这是一个驻留在设备上的矢量,所以您首先需要将其移动到主机上。