我有很多 32b 值,我需要计算整个数据长度上每个第 n 个真位的出现次数,并且我需要尽快完成,因为这是整个模拟的性能瓶颈。我创建了一个简单的 C++ 方法,对 8 位值执行此操作来说明问题:
#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;
}
Run Code Online (Sandbox Code Playgroud)
是否有一种算法可以完成相同的操作但速度更快?
下面是一种可能方法的草图(如果您可以将输入调整为 8 字节的倍数,或者如果您预先知道向量的大小,则可以对此进行很大改进)。但它让您了解如何使用 popcount。(对于 32 位架构,模式是相同的,但性能较低)
// #include <intrin.h> // for popcnt which counts number of set bits in a variable
#include <array>
#include <iostream>
#include <vector>
#include <cstdint>
#include <memory>
// work on copy on purpose so we can pad memory of vector to 64bit alignment (kind of a quick hack for now, the extra memory (re)allocations might slow you down too much)
auto vertical_popcount(std::vector<std::uint8_t> values)
{
// use 64bit architecture to do 8 values per cycle
static constexpr std::array<std::uint64_t, 8> masks
{
0x0101010101010101,
0x0202020202020202,
0x0404040404040404,
0x0808080808080808,
0x1010101010101010,
0x2020202020202020,
0x4040404040404040,
0x8080808080808080
};
//using an array instead of vector safes at least one dynamic allocation
std::array<std::size_t, 8> counts{};
// align data to multiple of 8 bytes
// add a few extra 0 bytes, they wont impact the counting
for (std::size_t n = 0; n < values.size() % 8; ++n)
values.push_back(0);
// make a uint64_t pointer into 8 bit data
// to pickup 8 bytes at a time for masking
auto ptr = reinterpret_cast<std::uint64_t*>(values.data());
for (std::size_t n = 0; n < values.size() / 8; ++n)
{
for (std::size_t m = 0; m < 8; ++m)
{
// mask 8 bytes at a time
auto masked_value = (*ptr & masks[m]);
// count bits of 8 uint8_t's in one loop
auto bitcount = std::popcount(masked_value);
counts[m] += bitcount;
}
++ptr;
}
return counts;
}
int main()
{
std::vector<uint8_t> data({ 0b00001001, 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |