I have a lot of 32b values and I need to count the occurrence of each nth true bit over the entire length of the data and I need to do it as fast as possible because this is the performance bottleneck of the whole simulation. I created a naive c++ approach that does this for 8 bit values to illustrate the question:
#include <iostream>
#include <vector>
#include <cstdint>
std::vector<uint32_t> vertical_popcount(std::vector<uint8_t>& data) {
std::vector<uint32_t> result({0, 0, 0, 0, 0, 0, 0, 0});
for (auto i = 0; i < data.size(); i++) {
result[0] += (data[i] & 0b10000000) > 0;
result[1] += (data[i] & 0b01000000) > 0;
result[2] += (data[i] & 0b00100000) > 0;
result[3] += (data[i] & 0b00010000) > 0;
result[4] += (data[i] & 0b00001000) > 0;
result[5] += (data[i] & 0b00000100) > 0;
result[6] += (data[i] & 0b00000010) > 0;
result[7] += (data[i] & 0b00000001) > 0;
}
return result;
}
int main() {
std::vector<uint8_t> data({0b00000001, 0b00000100, 0b00000101});
auto result = vertical_popcount(data);
std::cout << "occurrence of bits: " << result[0] << ", " << result[1] << ", " << result[2] << ", " << result[3] << ", " << result[4] << ", " << result[5] << ", " << result[6] << ", " << result[7] << "\n";
return 0;
}
Is there an algorithm that does the same but (much) faster?