我有几个块,每个块在整数数组的单独部分上执行.例如:阻塞一个从数组[0]到数组[9],阻塞二从数组[10]到数组[20].
我可以获得每个块的数组最大值索引的最佳方法是什么?
示例块a a [0]到[10]具有以下值:
5 10 2 3 4 34 56 3 9 10
所以56是指数6的最大值.
我无法使用共享内存,因为数组的大小可能非常大.因此它不适合.是否有任何图书馆允许我这么快?
我知道减少算法,但我认为我的情况不同,因为我想得到最大元素的索引.
如果我确切地理解你想要的是:获取数组 A 中最大值的索引。
如果这是真的,那么我建议您使用推力库:
以下是您的操作方法:
#include <thrust/device_vector.h>
#include <thrust/tuple.h>
#include <thrust/reduce.h>
#include <thrust/fill.h>
#include <thrust/generate.h>
#include <thrust/sort.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <cstdlib>
#include <time.h>
using namespace thrust;
// return the biggest of two tuples
template <class T>
struct bigger_tuple {
__device__ __host__
tuple<T,int> operator()(const tuple<T,int> &a, const tuple<T,int> &b)
{
if (a > b) return a;
else return b;
}
};
template <class T>
int max_index(device_vector<T>& vec) {
// create implicit index sequence [0, 1, 2, ... )
counting_iterator<int> begin(0); counting_iterator<int> end(vec.size());
tuple<T,int> init(vec[0],0);
tuple<T,int> smallest;
smallest = reduce(make_zip_iterator(make_tuple(vec.begin(), begin)), make_zip_iterator(make_tuple(vec.end(), end)),
init, bigger_tuple<T>());
return get<1>(smallest);
}
int main(){
thrust::host_vector<int> h_vec(1024);
thrust::sequence(h_vec.begin(), h_vec.end()); // values = indices
// transfer data to the device
thrust::device_vector<int> d_vec = h_vec;
int index = max_index(d_vec);
std::cout << "Max index is:" << index <<std::endl;
std::cout << "Value is: " << h_vec[index] <<std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |