Вычисление произведения значений на основе битовых значений другого вектора с использованием SIMD - PullRequest
2 голосов
/ 07 ноября 2019

У меня есть два вектора. Вектор чисел a размера N и вектор беззнаковых символов b размера ceil(N/8). Цель состоит в том, чтобы вычислить произведение некоторых значений a. b должно считываться по битам, где каждый бит указывает, следует ли учитывать в продукте значение double из a.

  // Let's create some data      
  unsigned nbBits  = 1e7;
  unsigned nbBytes = nbBits / 8;
  unsigned char nbBitsInLastByte = nbBits % 8;
  assert(nbBits == nbBytes * 8 + nbBitsInLastByte);
  std::vector<double> a(nbBits, 0.999999);   // In practice a values will vary. It is just an easy to build example I am showing here
  std::vector<unsigned char> b(nbBytes, false); // I am not using `vector<bool>` nor `bitset`. I've got my reasons!
  assert(a.size() == b.size() * 8);

  // Set a few bits to true
  for (unsigned byte = 0 ; byte < (nbBytes-1) ; byte+=2)
  {
    b[byte] |= 1 << 2; // set second (zero-based counting) bit to 'true'
    b[byte] |= 1 << 7; // set last bit to 'true'
                //  ^ This is the bit index
  }

Как объяснено выше,моя цель - вычислить произведение значений в a всякий раз, когда b истинно. Это может быть достигнуто с помощью

  // Initialize the variable we want to compute
  double product = 1.0;

  // Product for the first nbByts-1 bytes
  for (unsigned byte = 0 ; byte < (nbBytes-1) ; ++byte)
  {
    for (unsigned bit = 0 ; bit < 8 ; ++bit) // inner loop could be manually unrolled
    {
      if((b[byte] >> bit) & 1) // gets the bit value
        product *= a[byte*8+bit];
    }
  }

  // Product for the last byte
  for (unsigned bit = 0 ; bit < nbBitsInLastByte ; ++bit)
  {
    if((b[nbBytes-1] >> bit) & 1) // gets the bit value
      product *= a[(nbBytes-1)*8+bit];
  }

Это вычисление продукта является медленной частью моего кода. Я задаюсь вопросом, может ли явная векторизация (SIMD) процесса помочь здесь. Я просматривал функции, представленные в «xmmintrin.h», но я не очень разбираюсь в SIMD и не смог найти что-то, что могло бы помочь. Вы можете мне помочь?

...