我想使用CUDA的Thrust中的copy_if来压缩结构数组。 我的结构有一个id和一个分数。我想只复制满足最低分数的结构。阈值由用户设置。
struct is_bigger_than_threshold
{
__host__ __device__
bool operator()(const register x)
{
return (x.score > threshold);
}
};
答案 0 :(得分:2)
是的,这是可能的。仿函数需要接受struct作为其operator参数,并且需要包含所需阈值的存储。当使用仿函数时,该阈值可以作为参数传递。这是一个完整的例子:
$ cat t688.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/copy.h>
#include <iostream>
struct my_score {
int id;
int score;
};
const int dsize = 10;
struct copy_func {
int threshold;
copy_func(int thr) : threshold(thr) {};
__host__ __device__
bool operator()(const my_score &x){
return (x.score > threshold);
}
};
int main(){
thrust::host_vector<my_score> h_data(dsize);
thrust::device_vector<my_score> d_result(dsize);
int my_threshold = 50;
for (int i = 0; i < dsize; i++){
h_data[i].id = i;
h_data[i].score = i * 10;}
thrust::device_vector<my_score> d_data = h_data;
int rsize = thrust::copy_if(d_data.begin(), d_data.end(), d_result.begin(), copy_func(my_threshold)) - d_result.begin();
std::cout << "There were " << rsize << " entries with a score greater than " << my_threshold << std::endl;
return 0;
}
$ nvcc -o t688 t688.cu
$ ./t688
There were 4 entries with a score greater than 50
$