简体   繁体   English

如何获得Win32的核心数?

[英]How to get number of cores in Win32?

I'm writing a program in C on windows that needs to run as many threads as available cores.我正在 Windows 上用 C 编写一个程序,该程序需要运行与可用内核一样多的线程。 But I dont know how to get the number of cores.但我不知道如何获得核心数。 Any ideas?有任何想法吗?

You can call the GetSystemInfo WinAPI function;可以调用GetSystemInfo WinAPI 函数; it returns a SYSTEM_INFO struct, which has the number of processors (which is the number of cores on a system with multiple core CPUs).它返回一个SYSTEM_INFO结构,其中包含处理器数量(这是具有多个核心 CPU 的系统上的核心数量)。

您可以读取 NUMBER_OF_PROCESSORS 环境变量。

Even though the question deals with .NET and yours with C, the basic responses should help:即使这个问题涉及 .NET 而你的问题涉及 C,基本的回答应该会有所帮助:

Detecting the number of processors 检测处理器数量

Type "cmd" on windows startup and open "cmd.exe".在 Windows 启动时输入“cmd”并打开“cmd.exe”。 Now type in the following command:现在输入以下命令:

WMIC CPU Get /Format:List

You will find the entries like - "NumberOfCores" and "NumberOfLogicalProcessors".您会找到诸如“NumberOfCores”和“NumberOfLogicalProcessors”之类的条目。 Typically the logical-processors are achieved by threading.通常逻辑处理器是通过线程实现的。 Therefore the relation would typically go like;因此,这种关系通常会像这样;

NumberOfLogicalProcessors = NumberOfCores * Number-of-Threads-per-Core. NumberOfLogicalProcessors = NumberOfCores * 每核线程数。

Since each core serves a processing-unit, therefore with threading, logical-processing-unit is realized in real space.由于每个内核服务于一个处理单元,因此通过线程,逻辑处理单元是在现实空间中实现的。

More info here .更多信息在这里

As @Changming-Sun mentioned in a comment above, GetSysInfo returns the number of logical processors, which is not always the same as the number of processor cores.正如@Changming-Sun 在上面的评论中提到的,GetSysInfo 返回逻辑处理器的数量,这并不总是与处理器内核的数量相同。 On machines that support hyperthreading (including most modern Intel CPUs) more than one thread can run on the same core (technically, more than one thread will have its thread context loaded on the same core).在支持超线程(包括大多数现代 Intel CPU)的机器上,可以在同一个内核上运行多个线程(从技术上讲,多个线程将在同一个内核上加载其线程上下文)。 Getting the number of processor cores requires a call to GetLogicalProcessorInformation and a little bit of coding work.获得处理器内核的数量需要调用 GetLogicalProcessorInformation 和一些编码工作。 Basically, you get back a list of SYSTEM_LOGICAL_PROCESSOR_INFORMATION entries, and you have to count the number of entries with RelationProcessorCore set.基本上,您会得到一个 SYSTEM_LOGICAL_PROCESSOR_INFORMATION 条目列表,并且您必须计算具有 RelationProcessorCore 设置的条目数。 A good example of how to code this in the GetLogicalProcessorInformation documentation provided by Microsoft: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation如何在 Microsoft 提供的 GetLogicalProcessorInformation 文档中对此进行编码的一个很好的例子: https ://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM