簡體   English   中英

使用推力::reduce 計算 8 位整數向量的和而不會溢出

[英]Using thrust::reduce to compute the sum over a vector of 8 bit integers without overflow

我有一個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>(),
                                        0,
                                        thrust::plus<int>());

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

更像你的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM