微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用推力::减少计算8位整数向量的总和而不会溢出

如何解决使用推力::减少计算8位整数向量的总和而不会溢出

我有一个 uint8_t 类型的设备向量,如果可能,我想使用 thrust::reduce 计算它的总和。问题是我得到了溢出,因为总和将远大于 255。我认为下面的代码将通过将结果存储为 32 位整数来计算总和,但似乎并非如此。有什么好的方法可以做到这一点吗?

uint8_t * flags_d;
...
const int32_t N_CMP_BLOCKS = thrust::reduce( 
    thrust::device_pointer_cast( flags_d ),thrust::device_pointer_cast( flags_d ) + N,(int32_t) 0,thrust::plus<int32_t>() );

解决方法

我认为唯一可行的解​​决方案是使用 thrust::transform_reduce 在归约中的累加操作之前将 8 位输入数据显式转换为 32 位数量。所以我希望是这样的:

#include <thrust/transform_reduce.h>
#include <thrust/functional.h>
#include <thrust/execution_policy.h>

template<typename T1,typename T2>
struct char2int
{
  __host__ __device__ T2 operator()(const T1 &x) const
  {
    return static_cast<T2>(x);
  }
};

int main()
{
  unsigned char data[6] = {128,100,200,102,101,123};
  int result = thrust::transform_reduce(thrust::host,data,data + 6,char2int<unsigned char,int>(),thrust::plus<int>());

  std::cout << "Result is " << result << std::endl;
 
  return 0;
}

更像你的想法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。