這是這裏提供從沒有答案的列表中刪除這個問題非常晚的答案。我確信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