我如何检测 CPU 是否具有良好的 POPCNT 支持?

How do I detect whether the CPU has good POPCNT support?

我有两个版本的fast newline-counting routine。一种在较旧的硬件上运行,而另一种通过使用 POPCNT 指令运行得更快,该指令可用于较新的硬件(例如第 6 代英特尔 CPUs)。

现在我想为每个 CPU 使用最好的版本 — 我怎样才能知道它是否具有高性能的 POPCNT 实现?

执行cpuid指令。检查 ecx.

的第 23 位

https://en.wikipedia.org/wiki/CPUID

你可以做到 , or you could take a more civilised approach - the cpuid crate.

为此,请将其添加到您的 Cargo.toml,然后检查 POPCNT 是否可用

extern crate cpuid;

fn have_popcnt() -> Option<bool> {
    cpuid::identify().ok().map(|ci| ci.has_feature(cpuid::CpuFeature::POPCNT))
}

如果 CPU 不支持 CPUID 指令或 Some(hp)have_popcnt() 函数将 return None,其中hp 确定 POPCNT 的可用性。