简体   繁体   English

推力 CUDA 计算数组中每个段的索引

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

I have an array of int which serves as keys in my application.我有一个 int 数组,用作我的应用程序中的键。 This is already sorted.这已经排序了。 I want to assign each unique key a unique index starting from 0. How would I do that in cuda using thrust?我想为每个唯一键分配一个从 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}

Each segment can be of any arbitrary length.每个段可以是任意长度。

There are probably many ways to do it.可能有很多方法可以做到这一点。 One possible way: thrust::adjacent_difference() with a binary op that produces 0 when the values are the same and 1 in any other case, followed by a prefix sum .一种可能的方法: thrust::adjacent_difference()使用二进制操作,当值相同时生成 0,在任何其他情况下生成 1,后跟前缀 sum

Here is a worked example:这是一个工作示例:

$ 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