Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# (LocalAlloc(LMEM_FIXED,cb)); 如果(!m_pinfoBase)返回; 如果(!GetLogicalProcessorInformationEx(关系, m_pinfoBase和cb)返回; m_pinfoCurrent=m_pinfoBase; m_cbRemaining=cb; } ~EnumLogicalProcessorInformation(){LocalFree(m_pinfoBase);} void MoveNext() { 如果(m_pinfoCurrent){ m_cbRemaining-=m_pinfoCurrent->Size; 如果(m_cbRemaining){ m_pinfoCurrent=高级字节(m_pinfoCurrent, m_pinfoCurrent->Size); }否则{ m_pinfoCurrent=nullptr; } } } 系统逻辑处理器信息EX*Current() {返回m_pinfoCurrent;} 私人: 系统\逻辑\处理器\信息\ EX*m\ pinfoBase; 系统\逻辑\处理器\信息\ EX*m\ pinfoCurrent; 德沃德·穆卡雷曼; }; 内部cdecl主(内部argc,字符**argv) { 整数逻辑核=0; int numPhysicalCore=0; 用于(EnumLogicalProcessorInformation)enumInfo(RelationProcessorCore); 自动pinfo=enumInfo.Current();enumInfo.MoveNext()) { int numThreadPerCore=(pinfo->Processor.Flags==LTP\u PC\u SMT)?2:1; //一个选项是从注册表读取数据。 MSDN关于以下主题的文章:)_C#_.net_Cpu Cores - Fatal编程技术网

C# (LocalAlloc(LMEM_FIXED,cb)); 如果(!m_pinfoBase)返回; 如果(!GetLogicalProcessorInformationEx(关系, m_pinfoBase和cb)返回; m_pinfoCurrent=m_pinfoBase; m_cbRemaining=cb; } ~EnumLogicalProcessorInformation(){LocalFree(m_pinfoBase);} void MoveNext() { 如果(m_pinfoCurrent){ m_cbRemaining-=m_pinfoCurrent->Size; 如果(m_cbRemaining){ m_pinfoCurrent=高级字节(m_pinfoCurrent, m_pinfoCurrent->Size); }否则{ m_pinfoCurrent=nullptr; } } } 系统逻辑处理器信息EX*Current() {返回m_pinfoCurrent;} 私人: 系统\逻辑\处理器\信息\ EX*m\ pinfoBase; 系统\逻辑\处理器\信息\ EX*m\ pinfoCurrent; 德沃德·穆卡雷曼; }; 内部cdecl主(内部argc,字符**argv) { 整数逻辑核=0; int numPhysicalCore=0; 用于(EnumLogicalProcessorInformation)enumInfo(RelationProcessorCore); 自动pinfo=enumInfo.Current();enumInfo.MoveNext()) { int numThreadPerCore=(pinfo->Processor.Flags==LTP\u PC\u SMT)?2:1; //一个选项是从注册表读取数据。 MSDN关于以下主题的文章:)

C# (LocalAlloc(LMEM_FIXED,cb)); 如果(!m_pinfoBase)返回; 如果(!GetLogicalProcessorInformationEx(关系, m_pinfoBase和cb)返回; m_pinfoCurrent=m_pinfoBase; m_cbRemaining=cb; } ~EnumLogicalProcessorInformation(){LocalFree(m_pinfoBase);} void MoveNext() { 如果(m_pinfoCurrent){ m_cbRemaining-=m_pinfoCurrent->Size; 如果(m_cbRemaining){ m_pinfoCurrent=高级字节(m_pinfoCurrent, m_pinfoCurrent->Size); }否则{ m_pinfoCurrent=nullptr; } } } 系统逻辑处理器信息EX*Current() {返回m_pinfoCurrent;} 私人: 系统\逻辑\处理器\信息\ EX*m\ pinfoBase; 系统\逻辑\处理器\信息\ EX*m\ pinfoCurrent; 德沃德·穆卡雷曼; }; 内部cdecl主(内部argc,字符**argv) { 整数逻辑核=0; int numPhysicalCore=0; 用于(EnumLogicalProcessorInformation)enumInfo(RelationProcessorCore); 自动pinfo=enumInfo.Current();enumInfo.MoveNext()) { int numThreadPerCore=(pinfo->Processor.Flags==LTP\u PC\u SMT)?2:1; //一个选项是从注册表读取数据。 MSDN关于以下主题的文章:),c#,.net,cpu-cores,C#,.net,Cpu Cores,处理器,我相信可以在这里找到,HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor private void determineNumberOfProcessCores() { RegistryKey rk = Registry.LocalMachine; String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DES

处理器,我相信可以在这里找到,HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor

    private void determineNumberOfProcessCores()
    {
        RegistryKey rk = Registry.LocalMachine;
        String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();

        textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
    }
我有理由相信大多数系统上都会有注册表项


尽管我会投入0.02美元。

一个选择是从注册表读取数据。 MSDN关于以下主题的文章:)

处理器,我相信可以在这里找到,HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor

    private void determineNumberOfProcessCores()
    {
        RegistryKey rk = Registry.LocalMachine;
        String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();

        textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
    }
我有理由相信大多数系统上都会有注册表项


虽然我会投入0.02美元。

我也在寻找同样的东西,但我不想安装任何nuget或servicepack,所以我找到了这个解决方案,它非常简单和直接, 通过讨论,我认为运行WMIC命令并获得该值非常容易,下面是C代码。您只需要使用System.Management命名空间(并为流程等耦合更多标准命名空间)


我也在寻找同样的东西,但我不想安装任何nuget或servicepack,所以我找到了这个解决方案,它非常简单和直接, 通过讨论,我认为运行WMIC命令并获得该值非常容易,下面是C代码。您只需要使用System.Management命名空间(并为流程等耦合更多标准命名空间)


看看.NET如何在内部实现这一点非常有趣,至少可以这么说……它的“简单”如下所示:

namespace System.Threading
{
    using System;
    using System.Runtime.CompilerServices;

    internal static class PlatformHelper
    {
        private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
        private static volatile int s_lastProcessorCountRefreshTicks;
        private static volatile int s_processorCount;

        internal static bool IsSingleProcessor
        {
            get
            {
                return (ProcessorCount == 1);
            }
        }

        internal static int ProcessorCount
        {
            get
            {
                int tickCount = Environment.TickCount;
                int num2 = s_processorCount;
                if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
                {
                    s_processorCount = num2 = Environment.ProcessorCount;
                    s_lastProcessorCountRefreshTicks = tickCount;
                }
                return num2;
            }
        }
    }
}

看看.NET如何在内部实现这一点非常有趣,至少可以这么说……它的“简单”如下所示:

namespace System.Threading
{
    using System;
    using System.Runtime.CompilerServices;

    internal static class PlatformHelper
    {
        private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
        private static volatile int s_lastProcessorCountRefreshTicks;
        private static volatile int s_processorCount;

        internal static bool IsSingleProcessor
        {
            get
            {
                return (ProcessorCount == 1);
            }
        }

        internal static int ProcessorCount
        {
            get
            {
                int tickCount = Environment.TickCount;
                int num2 = s_processorCount;
                if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
                {
                    s_processorCount = num2 = Environment.ProcessorCount;
                    s_lastProcessorCountRefreshTicks = tickCount;
                }
                return num2;
            }
        }
    }
}
来自.NETFramework源代码 您还可以使用
Kernel32.dll上的PInvoke获取它

以下代码或多或少来自System.Web源中的
SystemInfo.cs

来自.NETFramework源代码 您还可以使用
Kernel32.dll上的PInvoke获取它

以下代码或多或少来自System.Web源中的
SystemInfo.cs


最简单的方式=
环境。处理器计数

举例


最简单的方式=
环境。处理器计数

举例


这里已经有很多答案了,但有些答案的得票率很高,是不正确的

.NET Environment.ProcessorCount将返回不正确的值,如果系统WMI配置不正确,可能会严重失败

如果您想要一种可靠的计算内核的方法,唯一的方法就是Win32 API

这是一个C++片段:

#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}
#包括
#包括
int num_物理_cores()
{
静态int num_cores=[]
{
DWORD字节=0;
GetLogicalProcessorInformation(空ptr和字节);
std::vector coreInfo(字节/大小(系统逻辑处理器信息));
GetLogicalProcessorInformation(coreInfo.data(),&bytes);
int核=0;
用于(自动和信息:coreInfo)
{
if(info.Relationship==RelationProcessorCore)
++核心;
}
返回磁芯>0?磁芯:1;
}();
返回核数;
}
由于这是一个.NET C#问题,下面是移植版本:

[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();
[StructLayout(LayoutKind.Sequential)]
结构缓存描述符
{
公共字节级;
公共字节关联性;
公共ushort线尺寸;
公共单位面积;
公共uint类型;
}
[StructLayout(LayoutKind.Explicit)]
结构系统逻辑处理器信息联合
{
[FieldOffset(0)]公共字节处理器核心;
[FieldOffset(0)]公共单位纽曼诺德;
[FieldOffset(0)]公共缓存\描述符缓存;
[FieldOffset(0)]保留的专用UInt64 1;
[FieldOffset(8)]私人UInt64保留区2;
}
公共枚举逻辑处理器关系
{
关系处理中心,
关系纽曼诺德,
关系缓存,
关系处理程序包,
关系组,
关系L=0xffff
}
结构系统\逻辑\处理器\信息
{
公共UIntPtr处理器任务;
公共逻辑处理器关系;
公共系统\逻辑\处理器\信息\联合处理器信息;
}
[DllImport(“kernel32.dll”)]
静态外部不安全bool getLogicalProcessor信息(系统逻辑处理器信息*缓冲区,out int bufferSize);
静态不安全int GetProcessorCoreCount()
{
GetLogicalProcessorInformation(null,out int bufferSize);
int numEntries=bufferSize/sizeof(系统逻辑处理器信息);
var coreInfo=新系统逻辑处理器信息[numEntries];
修复(系统逻辑处理器信息*pCoreInfo=coreInfo)
{
GetLogicalProcessorInformation(pCoreInfo,输出缓冲区大小);
int核=0;
对于(int i=0;i<
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())
#define STRICT
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <omp.h>

template<typename T>
T *AdvanceBytes(T *p, SIZE_T cb)
{
 return reinterpret_cast<T*>(reinterpret_cast<BYTE *>(p) + cb);
}

class EnumLogicalProcessorInformation
{
public:
 EnumLogicalProcessorInformation(LOGICAL_PROCESSOR_RELATIONSHIP Relationship)
  : m_pinfoBase(nullptr), m_pinfoCurrent(nullptr), m_cbRemaining(0)
 {
  DWORD cb = 0;
  if (GetLogicalProcessorInformationEx(Relationship,
                                       nullptr, &cb)) return;
  if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return;

  m_pinfoBase =
   reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *>
                                     (LocalAlloc(LMEM_FIXED, cb));
  if (!m_pinfoBase) return;

  if (!GetLogicalProcessorInformationEx(Relationship, 
                                        m_pinfoBase, &cb)) return;

  m_pinfoCurrent = m_pinfoBase;
  m_cbRemaining = cb;
 }

 ~EnumLogicalProcessorInformation() { LocalFree(m_pinfoBase); }

 void MoveNext()
 {
  if (m_pinfoCurrent) {
   m_cbRemaining -= m_pinfoCurrent->Size;
   if (m_cbRemaining) {
    m_pinfoCurrent = AdvanceBytes(m_pinfoCurrent,
                                  m_pinfoCurrent->Size);
   } else {
    m_pinfoCurrent = nullptr;
   }
  }
 }

 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *Current()
                                         { return m_pinfoCurrent; }
private:
 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *m_pinfoBase;
 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *m_pinfoCurrent;
 DWORD m_cbRemaining;
};


int __cdecl main(int argc, char **argv)
{
  int numLogicalCore = 0;
  int numPhysicalCore = 0;

  for (EnumLogicalProcessorInformation enumInfo(RelationProcessorCore);
      auto pinfo = enumInfo.Current(); enumInfo.MoveNext()) 
  {
      int numThreadPerCore = (pinfo->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
      // std::cout << "thread per core: "<< numThreadPerCore << std::endl;
      numLogicalCore += numThreadPerCore;
      numPhysicalCore += 1;
  }

  printf ("Number of physical core = %d , Number of Logical core = %d \n", numPhysicalCore, numLogicalCore );

 char c = getchar(); /* just to wait on to see the results in the command prompt */
 return 0;
}

/*
I tested with Intel Xeon four cores with hyper threading and here is the result
Number of physical core = 4 , Number of Logical core = 8
*/
    private void determineNumberOfProcessCores()
    {
        RegistryKey rk = Registry.LocalMachine;
        String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();

        textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
    }
string fileName = Path.Combine(Environment.SystemDirectory, "wbem", "wmic.exe");
string arguments = @"cpu get NumberOfCores";

Process process = new Process
{
    StartInfo =
    {
        FileName = fileName,
        Arguments = arguments,
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    }
};

process.Start();

StreamReader output = process.StandardOutput;
Console.WriteLine(output.ReadToEnd());


process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();
namespace System.Threading
{
    using System;
    using System.Runtime.CompilerServices;

    internal static class PlatformHelper
    {
        private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
        private static volatile int s_lastProcessorCountRefreshTicks;
        private static volatile int s_processorCount;

        internal static bool IsSingleProcessor
        {
            get
            {
                return (ProcessorCount == 1);
            }
        }

        internal static int ProcessorCount
        {
            get
            {
                int tickCount = Environment.TickCount;
                int num2 = s_processorCount;
                if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
                {
                    s_processorCount = num2 = Environment.ProcessorCount;
                    s_lastProcessorCountRefreshTicks = tickCount;
                }
                return num2;
            }
        }
    }
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_INFO
{
  public ushort wProcessorArchitecture;
  public ushort wReserved;
  public uint dwPageSize;
  public IntPtr lpMinimumApplicationAddress;
  public IntPtr lpMaximumApplicationAddress;
  public IntPtr dwActiveProcessorMask;
  public uint dwNumberOfProcessors;
  public uint dwProcessorType;
  public uint dwAllocationGranularity;
  public ushort wProcessorLevel;
  public ushort wProcessorRevision;
}

internal static class SystemInfo 
{
    static int _trueNumberOfProcessors;
    internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);    

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    internal static extern void GetSystemInfo(out SYSTEM_INFO si);

    [DllImport("kernel32.dll")]
    internal static extern int GetProcessAffinityMask(IntPtr handle, out IntPtr processAffinityMask, out IntPtr systemAffinityMask);

    internal static int GetNumProcessCPUs()
    {
      if (SystemInfo._trueNumberOfProcessors == 0)
      {
        SYSTEM_INFO si;
        GetSystemInfo(out si);
        if ((int) si.dwNumberOfProcessors == 1)
        {
          SystemInfo._trueNumberOfProcessors = 1;
        }
        else
        {
          IntPtr processAffinityMask;
          IntPtr systemAffinityMask;
          if (GetProcessAffinityMask(INVALID_HANDLE_VALUE, out processAffinityMask, out systemAffinityMask) == 0)
          {
            SystemInfo._trueNumberOfProcessors = 1;
          }
          else
          {
            int num1 = 0;
            if (IntPtr.Size == 4)
            {
              uint num2 = (uint) (int) processAffinityMask;
              while ((int) num2 != 0)
              {
                if (((int) num2 & 1) == 1)
                  ++num1;
                num2 >>= 1;
              }
            }
            else
            {
              ulong num2 = (ulong) (long) processAffinityMask;
              while ((long) num2 != 0L)
              {
                if (((long) num2 & 1L) == 1L)
                  ++num1;
                num2 >>= 1;
              }
            }
            SystemInfo._trueNumberOfProcessors = num1;
          }
        }
      }
      return SystemInfo._trueNumberOfProcessors;
    }
}
using System;

class Sample 
{
    public static void Main() 
    {
        Console.WriteLine("The number of processors " +
            "on this computer is {0}.", 
            Environment.ProcessorCount);
    }
}
#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}
[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();
public static class CpuCores
{
    private static int cores = 0;
    
    public static int Number
    { 
        get
        {
            if (cores > 0) return cores;

            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" +
                "{50127dc3-0f36-415e-a6cc-4cb3be910b65}");
            if (key == null)
            {
                cores = Environment.ProcessorCount;
                return cores;
            }
            string[] subkeys = key.GetSubKeyNames();
            key.Close();
            cores = 0;
            if (subkeys != null && subkeys.Length > 0) foreach (string s in subkeys)
            {
                if (s.Length != 4) continue;
                int n;
                if (int.TryParse(s, out n) && ++n > cores) cores = n;
            }
            if (cores <= 0) cores = Environment.ProcessorCount;
            return cores;
        } 
    }
}