Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two versions of a fast newline-counting routine. One runs on older hardware, while the other one runs much faster by using the POPCNT instruction, which is available on newer hardware (e.g. 6th generation Intel CPUs).

Now I'd like to use the best version for each CPU — how can I find out if it has a high-performance POPCNT implementation?

like image 868
llogiq Avatar asked Sep 23 '16 23:09

llogiq


2 Answers

You could do like @kobrien said, or you could take a more civilised approach - the cpuid crate.

To do that, add it to your Cargo.toml and then, to check for availability of the POPCNT do

extern crate cpuid;

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

The have_popcnt() function will return None if the CPU doesn't support the CPUID instruction or Some(hp), where hp determines POPCNT's availability thereon.

like image 88
набиячлэвэли Avatar answered Oct 23 '22 07:10

набиячлэвэли


Execute the cpuid instruction. Check bit 23 of ecx.

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

like image 42
kobrien Avatar answered Oct 23 '22 09:10

kobrien