使用包含推力的每个重复次数的列表生成重复的升序整数序列

问题描述 投票:-1回答:1

我想生成一系列重复的升序整数,给出一个列表,其中包含每个整数所需的重复次数:

thrust::device_vector<int> reps {3, 2, 5, 1};
//This vector should yield a resulting list:
// {0,0,0, 1,1, 2,2,2,2,2, 3}

理想情况下,我想使用推力API来做到这一点。

我考虑过这种方法:

  1. 前缀汇总代表列表以生成累积代表列表。
  2. 使用累积reps列表中的final元素分配生成的整数向量。
  3. 使用内核,为reps列表的每个元素运行一个线程,并从i = 0 : reps[tid]循环,在tid存储cumulative_reps[tid]+i

这可行,但最终可能会连续完成大部分工作,并且无法使用CUDA。

我想知道是否有推力迭代器和算法的组合来简洁地生成整数列表?或者,一个比我概述的更好的方法,即使没有推力,也会很棒。

c++ parallel-processing cuda thrust
1个回答
2
投票

您可以使用与您类似的方法完全按推力执行此操作。

  1. 对输入执行前缀求和以确定步骤2的结果大小,以及步骤3的散点索引
  2. 创建输出向量以保存结果
  3. 将1分散到输出向量中的适当位置,由步骤1的索引给出
  4. 在输出向量上执行前缀和。

请注意,如果允许输入reps向量包含值0,则必须修改此方法。

这是一个有效的例子:

$ cat t404.cu
#include <thrust/scan.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/permutation_iterator.h>
#include <iostream>

int main(){

  int host_reps[] = {3, 2, 5, 1};
  int ds = sizeof(host_reps)/sizeof(int);
  thrust::device_vector<int> reps(host_reps, host_reps+ds);
  thrust::inclusive_scan(reps.begin(), reps.end(), reps.begin());
  thrust::device_vector<int> result(reps[reps.size()-1]);
  thrust::copy_n(thrust::constant_iterator<int>(1), reps.size()-1, thrust::make_permutation_iterator(result.begin(), reps.begin()));
  thrust::inclusive_scan(result.begin(), result.end(), result.begin());
  thrust::copy_n(result.begin(), result.size(), std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;
}
$ nvcc -o t404 t404.cu
$ ./t404
0,0,0,1,1,2,2,2,2,2,3,
$
© www.soinside.com 2019 - 2024. All rights reserved.