从C#检查CPU数量#

问题描述:

有谁知道如何检查C#中的CPU,如果它支持popcount(人口数量)? C++很容易,但试图用一些国际象棋代码做一些C++到C#的转换。从C#检查CPU数量#

非常感谢。

+0

您是否需要在特定时间点查找CPU使用情况? – 2011-05-23 13:25:32

+0

在C++中,这需要特定于实现的编译器,例如, '__builtin_popcount'(用于gcc)。 – 2011-05-23 13:49:51

欢迎来到Stackoverflow :) 我发现这个问题,似乎是这个类似,也许你会发现它也很有帮助。

Elegantly determine if more than one boolean is "true"

您也可以看看bit operators是在C#以及this article

CNC中

而且更直接awnser你的问题,因为C#编译为IL不到机器代码,你真的不能做cpu级别的优化。公共语言运行库中的JIT编译器能够在代码实际运行时进行一些优化,但不能从语言本身直接访问该进程。

但是,您可以混合使用C++和托管代码,做你的低级别的优化存在,但它那种失败移动到C#

+0

非常感谢您的信息。我会检查出来的。 – David 2011-05-23 13:47:53

我还没有找到一个简单的方法来检测,并使用特殊的CPU指令的目的在C#中。有几种选择,没有一个很好。

  • asmjit,做popcount
  • x86/x64 CPUID in C#
  • 单功能与数据类型支持的SIMD库(不popcount我猜)
  • 使用C++ DLL(可能的方式慢,因为开销)
  • ..

我从来没有这样做过,并实现了一个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); 
    }