Win32下如何获取核心数?
我正在 Windows 上用 C 编写一个程序,需要运行与可用内核一样多的线程。但我不知道如何获得核心数。有什么想法吗?
I'm writing a program in C on windows that needs to run as many threads as available cores. But I dont know how to get the number of cores. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以调用
GetSystemInfo
WinAPI函数;它返回一个 SYSTEM_INFO 结构,其中包含处理器的数量(即具有多核 CPU 的系统上的核心数量)。You can call the
GetSystemInfo
WinAPI function; it returns aSYSTEM_INFO
struct, which has the number of processors (which is the number of cores on a system with multiple core CPUs).您可以读取 NUMBER_OF_PROCESSORS 环境变量。
You can read NUMBER_OF_PROCESSORS environment variable.
正如@Changming-Sun 在上面的评论中提到的,GetSysInfo 返回逻辑处理器的数量,它并不总是与处理器核心的数量相同。在支持超线程的机器(包括大多数现代 Intel CPU)上,同一内核上可以运行多个线程(从技术上讲,多个线程将在同一内核上加载其线程上下文)。获取处理器核心的数量需要调用 GetLogicalProcessorInformation 和一些编码工作。基本上,您会返回 SYSTEM_LOGICAL_PROCESSOR_INFORMATION 条目的列表,并且必须计算设置了 RelationProcessorCore 的条目数。 Microsoft 提供的 GetLogicalProcessorInformation 文档中提供了有关如何对此进行编码的一个很好的示例:
https://learn.microsoft.com/ en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-get逻辑处理器信息
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. 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). Getting the number of processor cores requires a call to GetLogicalProcessorInformation and a little bit of coding work. Basically, you get back a list of SYSTEM_LOGICAL_PROCESSOR_INFORMATION entries, and you have to count the number of entries with RelationProcessorCore set. A good example of how to code this in the GetLogicalProcessorInformation documentation provided by Microsoft:
https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation
在 Windows 启动时键入“cmd”并打开“cmd.exe”。
现在输入以下命令:
您将找到类似“NumberOfCores”和“NumberOfLogicalProcessors”的条目。通常,逻辑处理器是通过线程实现的。因此,这种关系通常会像这样:
NumberOfLogicalProcessors = NumberOfCores * Number-of-Threads-per-Core。
由于每个核心服务一个处理单元,因此通过线程,逻辑处理单元是在实际空间中实现的。
更多信息此处。
Type "cmd" on windows startup and open "cmd.exe".
Now type in the following command:
You will find the entries like - "NumberOfCores" and "NumberOfLogicalProcessors". Typically the logical-processors are achieved by threading. Therefore the relation would typically go like;
NumberOfLogicalProcessors = NumberOfCores * Number-of-Threads-per-Core.
Since each core serves a processing-unit, therefore with threading, logical-processing-unit is realized in real space.
More info here.
即使问题涉及 .NET 而您的问题涉及 C,基本回答应该会有所帮助:
检测数量处理器数量
Even though the question deals with .NET and yours with C, the basic responses should help:
Detecting the number of processors