[英]Count reduction using Thrust
给定一些输入键和值,我试图计算存在多少具有相同键的连续值。 我将举一个例子来说明这一点。
输入键: { 1, 4, 4, 4, 2, 2, 1 }
输入值: { 9, 8, 7, 6, 5, 4, 3 }
预期的输出键: { 1, 4, 2, 1 }
1,4,2,1 { 1, 4, 2, 1 }
预期输出值: { 1, 3, 2, 1 }
1,3,2,1 { 1, 3, 2, 1 }
我试图使用CUDA在GPU上解决这个问题。 Thrust库的减少功能似乎是一个很好的解决方案,我得到了以下内容:
#include <thrust/reduce.h>
#include <thrust/functional.h>
struct count_functor : public thrust::binary_function<int, int, int>
{
__host__ __device__
int operator()(int input, int counter)
{
return counter + 1;
}
};
const int N = 7;
int A[N] = { 1, 4, 4, 4, 2, 2, 1 }; // input keys
int B[N] = { 9, 8, 7, 6, 5, 4, 3 }; // input values
int C[N]; // output keys
int D[N]; // output values
thrust::pair<int*, int*> new_end;
thrust::equal_to<int> binary_pred;
count_functor binary_op;
new_end = thrust::reduce_by_key(A, A + N, B, C, D, binary_pred, binary_op);
for (int i = 0; i < new_end.first - C; i++) {
std::cout << C[i] << " - " << D[i] << "\n";
}
此代码与Thrust文档中的示例非常相似。 但是,我试图计算,而不是plus
操作。 此代码的输出如下:
1 - 9
4 - 7
2 - 5
1 - 3
但是,我希望第二列包含值1, 3, 2, 1
。 我认为计数是关闭的,因为减少从它找到的第一个值开始,并且在它有第二个值之前不应用运算符,但我不确定是这种情况。
我是否忽略了一些可以解决这个问题的reduce_by_key
函数,或者我应该使用一个完全不同的函数来实现我想要的东西?
对于您的用例,您不需要B
的值, D
的值仅取决于A
的值。
为了计算A
有多少个连续值,你可以提供一个thrust::constant_iterator
作为输入值并应用thrust::reduce_by_key
:
#include <thrust/reduce.h>
#include <thrust/functional.h>
#include <iostream>
#include <thrust/iterator/constant_iterator.h>
int main()
{
const int N = 7;
int A[N] = { 1, 4, 4, 4, 2, 2, 1 };
int C[N];
int D[N];
thrust::pair<int*, int*> new_end;
thrust::equal_to<int> binary_pred;
thrust::plus<int> binary_op;
new_end = thrust::reduce_by_key(A, A + N, thrust::make_constant_iterator(1), C, D, binary_pred, binary_op);
for (int i = 0; i < new_end.first - C; i++) {
std::cout << C[i] << " - " << D[i] << "\n";
}
return 0;
}
产量
1 - 1
4 - 3
2 - 2
1 - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.