Does anyone know how to check from C# whether the CPU supports popcount (population count)?
I'm trying to port some chess code from C++ to C#.
Does anyone know how to check from C# whether the CPU supports popcount (population count)?
I'm trying to port some chess code from C++ to C#.
I have yet to find an easy way to detect and use special CPU instructions in C#. There are several options, none of them nice;
I never went that way and implemented a C# popcount;
/// <summary>
/// Count the number of bits set to 1 in a ulong
/// </summary>
public static byte BitCount(this ulong value)
{
ulong result = value - ((value >> 1) & 0x5555555555555555UL);
result = (result & 0x3333333333333333UL) + ((result >> 2) & 0x3333333333333333UL);
return (byte)(unchecked(((result + (result >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56);
}
Starting in .NET Core 3.0, you can use Popcnt.IsSupported
to test for the underlying hardware support.
Or, if you just need the result, use BitOperations.PopCount
. The methods in the BitOperations
class "use hardware intrinsics when available on the underlying platform; otherwise, they use optimized software fallbacks".
Since C# is compiled to IL not to machine code, you cant really do CPU level optimizations. The JIT compiler in the common language runtime is able to do some optimization when the code is actually run, but there is no direct access to that process from the language itself.
You can however mix C++ and managed code and do your low level optimizations there, but it kind of defeats the purpose of moving to C#.