簡體   English   中英

推力 CUDA 計算數組中每個段的索引

[英]Thrust CUDA compute index for each segment in an array

我有一個 int 數組,用作我的應用程序中的鍵。 這已經排序了。 我想為每個唯一鍵分配一個從 0 開始的唯一索引。我將如何使用推力在 cuda 中做到這一點?

    int* sorted_keys = {1, 1, 1, 13, 13, 13, 13, 13, 19, 19, 20}
    // Some thrust operation to get a new array as
    index_for_sorted_keys = {0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 3}

每個段可以是任意長度。

可能有很多方法可以做到這一點。 一種可能的方法: thrust::adjacent_difference()使用二進制操作,當值相同時生成 0,在任何其他情況下生成 1,后跟前綴 sum

這是一個工作示例:

$ cat t1537.cu
#include <thrust/adjacent_difference.h>
#include <thrust/scan.h>
#include <thrust/device_vector.h>
#include <iostream>
#include <thrust/copy.h>

using namespace thrust::placeholders;
int main(){

    int sorted_keys[] = {1, 1, 1, 13, 13, 13, 13, 13, 19, 19, 20};
    int ds = sizeof(sorted_keys)/sizeof(sorted_keys[0]);
    thrust::device_vector<int> d_sk(sorted_keys, sorted_keys+ds);
    thrust::device_vector<int> d_r(d_sk.size());
    thrust::adjacent_difference(d_sk.begin(), d_sk.end(), d_r.begin(), !(_1==_2));
    d_r[0] = 0;
    thrust::inclusive_scan(d_r.begin(), d_r.end(), d_r.begin());
    thrust::copy(d_r.begin(), d_r.end(), std::ostream_iterator<int>(std::cout, ","));
    std::cout << std::endl;
    return 0;
}
$ nvcc -o t1537 t1537.cu
$ ./t1537
0,0,0,1,1,1,1,1,2,2,3,
$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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