簡體   English   中英

使用Thrust減少計數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM