gpt4 book ai didi

cuda - 查找 CUDA 数组中每个不同值的第一个索引

转载 作者:行者123 更新时间:2023-12-04 22:55:45 25 4
gpt4 key购买 nike

假设我们有一个这样的数组:

0, 0, 0, 1, 2, 2, 2, 3, 3, 4, ...

我想要每个值第一次出现的索引,所以在这个例子中 [0, 3, 4, 7, 9]。数组已排序,所有可能的值都是已知且连续的。

我可能的解决方案是为这个数组中的每个元素使用一个内核,并使用 atomicmin 来保存最低索引。但我认为可能有更好的方法。

最佳答案

您只需调用 thrust::unique_by_key() 即可完成此操作。如果您提供索引向量,例如通过 thrust::sequence() .这是一个工作示例:

$ cat t3.cu
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/unique.h>
#include <thrust/sequence.h>
#include <iostream>

int main(){

int keys[] = {0, 0, 0, 1, 2, 2, 2, 3, 3, 4};
int ks = sizeof(keys)/sizeof(keys[0]);
thrust::device_vector<int> d_keys(keys, keys+ks);
thrust::device_vector<int> d_result(ks);
thrust::sequence(d_result.begin(), d_result.end());
int rs = (thrust::unique_by_key(d_keys.begin(), d_keys.end(), d_result.begin())).first - d_keys.begin();
thrust::copy_n(d_result.begin(), rs, std::ostream_iterator<int>(std::cout, ","));
std::cout << std::endl;
}

$ nvcc -arch=sm_35 -o t3 t3.cu
$ ./t3
0,3,4,7,9,
$

这里发生的重要事件是流压实,推力提供了 nice set of routines适用于各种用例。例如,这个操作也可以用 thrust::unique_copy() 来完成。在这种情况下,通过一些额外的代码复杂性,您可以消除对 thrust::sequence() 的需要。调用(它将被替换为 thrust::counting_iterator 与您的数据一起压缩,以及适当的选择仿函数),但它仍然需要相同长度的输出向量。

关于cuda - 查找 CUDA 数组中每个不同值的第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47815655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com