2012-05-04 56 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的可能性,您應該注意到這是一個駐留在設備上的矢量,所以您首先需要將其移動到主機上。