c++ - 获取 CUDA thrust::transform operator() 函数中的 vector 索引

标签 c++ cuda thrust

在 CUDA Thrust 变换中,是否可以在函数内部获取传递给 operator() 函数的 vector 的索引?

说,我们有,

struct op{
    float operator()(const float& f){
        //do something like return the index
    }
};
vector<float> v(100);
thrust::transform(v.begin(),v.end(),v.begin(),op());

如何获取 operator() 中 vector 的索引?基本上我想要一种在 CUDA 中制作单位矩阵的简单方法。

最佳答案

可能有很多方法可以做到这一点。一种方法是:

  1. 使用thrust::sequence创建一个与数据 vector 长度相同的索引 vector (或者只使用 counting_iterator )
  2. 使用zip_iterator返回 thrust::tuple ,结合数据 vector 和索引 vector ,返回一个数据项加上它的索引的元组
  3. 定义运算符op()将特定元组作为其参数之一
  4. 在运算符中,使用 thrust::get<>根据需要从元组中检索数据元素或索引

您可以在 thrust quickstart guide 中阅读有关其中大部分概念的更多信息.

编辑:为了回答下面的问题,这里有一个有效的例子。虽然这实际上并没有使用任何 device_vector ,如果我们在 GPU 上执行此操作(使用 device_vector ),唯一会产生任何重要 GPU 事件的事件就是调用 thrust::transform , IE。 GPU 上只有 1 个“通过”。

(是的,thrust::sequence 调用也会生成一个 GPU 内核,但我只是用它来为这个例子创建一些数据)。

#include <thrust/host_vector.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>

#define N 30
#define SELECT 3

typedef thrust::tuple<int, int>            tpl2int;
typedef thrust::host_vector<int>::iterator intiter;
typedef thrust::counting_iterator<int>     countiter;
typedef thrust::tuple<intiter, countiter>  tpl2intiter;
typedef thrust::zip_iterator<tpl2intiter>  idxzip;



struct select_unary_op : public thrust::unary_function<tpl2int, int>
{
  __host__ __device__
  int operator()(const tpl2int& x) const
  {
    if ((x.get<1>() %SELECT) == 0)
      return x.get<0>();
    else return -1;
   }
};

int main() {

  thrust::host_vector<int> A(N);
  thrust::host_vector<int> result(N);
  thrust::sequence(A.begin(), A.end());
  thrust::counting_iterator<int> idxfirst(0);
  thrust::counting_iterator<int> idxlast = idxfirst +N;

  idxzip first = thrust::make_zip_iterator(thrust::make_tuple(A.begin(), idxfirst));
  idxzip  last = thrust::make_zip_iterator(thrust::make_tuple(A.end(), idxlast));
  select_unary_op my_unary_op;

  thrust::transform(first, last, result.begin(), my_unary_op);
  std::cout << "Results :" << std::endl;
  thrust::copy(result.begin(), result.end(), std::ostream_iterator<int>( std::cout, " "));
  std::cout << std::endl;


  return 0;

}

关于c++ - 获取 CUDA thrust::transform operator() 函数中的 vector 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17484835/

相关文章:

c++ - 有异常的 Windows 并发运行时任务调度

arrays - 如何读回 CUDA 纹理进行测试?

c++ - 多重继承 - virtual 修饰符

c++ - 如何高效地创建 allegro 5 标题菜单?

c - 这将是均匀分布正态分布的最佳方法。将值放入桶中?

c++ - cuda示例代码中的.raw文件格式是什么?

performance - 如何以最大性能标准化 CUDA 中的矩阵列?

c++ - 我需要释放推力返回的 device_ptr 吗?

c - 使用 cuda Throw::max_element 查找数组中的最大元素有时返回不正确

c++ - 内联限定符源于原型(prototype)还是定义?