Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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# 单元尺寸; 公共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;i0?磁芯:1; } } public static readonly int NumPhysicalCores=GetProcessorCoreCount();_C#_.net_Cpu Cores - Fatal编程技术网

C# 单元尺寸; 公共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;i0?磁芯:1; } } public static readonly int NumPhysicalCores=GetProcessorCoreCount();

C# 单元尺寸; 公共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;i0?磁芯:1; } } public static readonly int NumPhysicalCores=GetProcessorCoreCount();,c#,.net,cpu-cores,C#,.net,Cpu Cores,您可以使用该类: public static class CpuCores { private static int cores = 0; public static int Number { get { if (cores > 0) return cores; RegistryKey key = Registry.LocalMachine.OpenSubKey(@&quo

您可以使用该类:

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;
        } 
    }
}
公共静态类CpuCores
{
私有静态int核=0;
公共静态整数
{ 
得到
{
如果(磁芯>0)返回磁芯;
RegistryKey key=Registry.LocalMachine.OpenSubKey(@“SYSTEM\CurrentControlSet\Control\Class\”+
“{50127dc3-0f36-415e-a6cc-4cb3be910b65}”;
if(key==null)
{
cores=Environment.ProcessorCount;
返回核心;
}
string[]subkeys=key.GetSubKeyNames();
key.Close();
核心=0;
if(子键!=null&&subkeys.Length>0)foreach(子键中的字符串s)
{
如果(s.长度!=4)继续;
int n;
如果(内部锥虫(s,out n)&++n>核心)核心=n;
}


如果(内核非常简单,我几乎要流眼泪了。谢谢你的回答!这给出了逻辑处理器的数量,而不是内核的数量。@KevinKibler从问题中,我怀疑OP不理解差异,如果你不知道差异,这可能就是你想要的。这还返回了许多内核的错误计数系统。我运行两个带超线程的dodeca core处理器,总共有48个逻辑处理器。
Environment.ProcessorCount
产生32个。@AlexanderMorou,是的,这将无法在一些多CPU服务器上提供准确的结果。对此有一个解决方案,但尚未测试。这给出了逻辑进程的数量essors,不是内核的数量。你需要知道有多少个内核或者有多少个逻辑处理器吗?对于只运行多个线程来说,两者都可能足够了,但在某些情况下,差异可能很重要。有没有更新的方法可以做到这一点?@StingyJack:是的,但我希望它的格式更好。Discoverabi当您必须构建原始字符串查询时,可用性非常低。WMI代码创建者将帮助您发现值和创建查询(它甚至可以在c#/vb.net中生成存根)。它位于System.Management.dll中。您是否在项目中包含对该程序集的引用?在上面的代码中只出现一个问题。由于
deviceCount
是基于零的,所以核心计数应如下输出:
Console.WriteLine(“核心数:{0}”,deviceCount+1);
您没有处理管理对象和搜索程序,这不是造成问题吗?您在什么系统上运行此操作?我使用多个“选择”查询并在部署我的软件的数千台计算机上进行测试,几乎不需要3.4秒。我执行Select*操作,因为我从该对象中获取多个属性。但是,我执行的操作有点不同:在Select*上创建ObjectQuery;获取ManagementObjectCollection;然后在管理中foreach ManagementObject“ElementObjectCollection”。@deegee:你说得对,使用“Select*”查询本身不会花费太多时间,只是如果迭代返回的所有值而不是NumberOfCores,下面的int解析会很慢。这将给出环境中已有的处理器数量。ProcessorCount,是否有其他类似的方法来获取每个处理器的内核数量?这个问题被标记为.NET;您的代码不是.NET代码。不确定原因您使一个简单的WMI查询变得如此复杂。将WMI命令行作为外部进程启动并解析其输出实际上是不必要的。.NET内置了对WMI查询的支持(System.Management.ManagementObjectSearcher)另外,我不知道为什么你认为在使用.NET的内置WMI支持而不是wmic.exe时需要nuget包或service Pack…如果有人想在Linux上运行C#代码,那里没有WMI。那么我们最好需要一个包含命令行和正则表达式的配置来解析输出,但his应该适合所有操作系统。或者您最好有一个接口IGetProcessorInfo和两个DLL(一个用于Windows,一个用于Linux)与相应的安装包一起交付并动态加载的?尝试此操作,但它返回逻辑处理器的数量-这与调用Environment.Processor的结果相同
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}
int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);
Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}
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;
        } 
    }
}