只计算向量CUDA/THRUST的正元素

coa*_*tal 2 cuda gpu gpgpu gpu-programming thrust

我想使用Thrust(因为我的大部分方法是使用推力数据类型实现)或C CUDA,如果需要,只能对向量的正浮点元素求和.数据最初未排序.我的初始刺伤非常糟糕:基本上,复制矢量,对其进行排序,通过将其传递到内核来找到零交叉,该内核比较顺序成对值并写入与零交叉匹配的内核.排序后基本上(我用Thrust做)...

int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n - 1) {
  float a = vector[i];
  float b = vector[i + 1];
  if (a >= 0.0 && b < 0.0)
    answer = i + 1;
}
Run Code Online (Sandbox Code Playgroud)

这真的是愚蠢的,很多线程匹配条件,太多的读取,分支差异等等.所以,它完全失败,每次调用将在相同的数据上给出不同的结果,等等.

我还没有找到一个在Thrust中实现这个的好方法,这是我更喜欢的.排序后我不知道如何找到过零点.有关跳跃点的建议吗?一个实际工作简单的CUDA C实现也会很好.

小智 5

要仅对正值求和,您不需要对初始值进行排序,请使用thrust :: transform_reduce:

template<typename T>
struct positive_value : public thrust::unary_function<T,T>
{
   __host__ __device__ T operator()(const T &x) const
   {
     return x < T(0) ? 0  : x;
   }
};

float result = thrust::transform_reduce(data.begin(), data.end(),
                                    positive_value<float>(),
                                    0,
                                    thrust::plus<float>());
Run Code Online (Sandbox Code Playgroud)