C++20 引入了许多新函数,例如 std::popcount
,我使用相同的功能使用 Intel Intrinsic .
我编译了两个选项 - 可以在 Compiler Explorer code 中看到:
- 使用 Intel 的 AVX2 intrinsic
- 使用 std::popcount 和 GCC 编译器标志“-mavx2”
除了 std 模板中使用的类型检查之外,生成的汇编代码看起来是一样的。
就与操作系统无关的代码和具有相同的优化而言 -
假设使用 std::popcount
和 apt 编译器 vector 优化标志比直接使用内部函数更好是正确的吗?
谢谢。
最佳答案
技术上不。(但实际上,是的)。 C++ 标准只指定了 popcount
的行为,而不是实现(引用[bit.count])。
实现者可以做任何他们想做的事情来实现这个行为,包括使用 popcnt
内在函数,但他们也可以编写一个 while 循环:
int set_bits = 0;
while(x)
{
if (x & 1)
++set_bits;
x >>= 1;
}
return set_bits;
这是标准中的完整措辞,位于 [bit.count] :
template<class T>
constexpr int popcount(T x) noexcept;
Constraints:
T
is an unsigned integer type ([basic.fundamental]).
Returns: The number of1
bits in the value ofx
.
现实吗?编译器编写者非常聪明,会对其进行优化以尽可能多地使用内部函数。例如,gcc's implementation似乎经过了相当程度的优化。
关于c++ - 使用 C++20 的 std::popcount 和 vector 优化是否等同于 popcnt 内在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65580986/