Checking CPU Popcount from 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;
- asmjit a function that does popcount
- x86/x64 CPUID in C#
- mono has a simd library with datatype support (not popcount I guess)
- Use a C++ DLL (probably way slower because of overhead)
- ..
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".
Welcome to Stackoverflow :) i found this question that seems to be similar to this one, perhaps you'll find it helpful as well.
Elegantly determine if more than one boolean is "true"
You can also look at the bit operators that are in c# as well as this article
-edit-
Also to awnser your question more directly, 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#
精彩评论