当你运行Mac OS X时,你如何从命令行得知机器上有多少核?在Linux上,我使用:

x=$(awk '/^processor/ {++n} END {print n+1}' /proc/cpuinfo)

虽然不完美,但已经很接近了。这是为了让feedto make,这就是为什么它给出的结果比实际数字高1。我知道上面的代码可以用Perl写得更密集,也可以用grep、wc和cut来写,但我认为上面的代码是简洁和可读性之间的一个很好的折衷。

非常晚的编辑:澄清一下:我问的是有多少逻辑核可用,因为这对应于我想要生成多少同步作业。jkp的回答,经过Chris Lloyd的进一步完善,正是我所需要的。YMMV。


当前回答

要在C中做到这一点,你可以使用sysctl(3)函数族:

int count;
size_t count_len = sizeof(count);
sysctlbyname("hw.logicalcpu", &count, &count_len, NULL, 0);
fprintf(stderr,"you have %i cpu cores", count);

用有趣的值来代替“hw”。Logicalcpu”,用于计算内核数,是(来自内核源代码中的注释):

hw.ncpu: The maximum number of processors that could be available this boot. Use this value for sizing of static per processor arrays; i.e. processor load statistics. hw.activecpu: The number of processors currently available for executing threads. Use this number to determine the number threads to create in SMP aware applications. This number can change when power management modes are changed. hw.physicalcpu: The number of physical processors available in the current power management mode. hw.physicalcpu_max: The maximum number of physical processors that could be available this boot. hw.logicalcpu: The number of logical processors available in the current power management mode. hw.logicalcpu_max: The maximum number of logical processors that could be available this boot.

其他回答

更简单:

sysctl -n hw.ncpu

正如jkp在评论中所说,这并没有显示物理内核的实际数量。要获取物理核数,可以使用以下命令:

system_profiler SPHardwareDataType

在最初的问题中没有指定(尽管我在评论中看到OP帖子说这不是一个选项),但macOS上的许多开发人员都安装了Homebrew包管理器。

对于未来偶然遇到这个问题的开发人员,只要存在安装Homebrew的假设(或需求)(例如,在公司的工程组织中),nproc就是coreutils包中包含的通用GNU二进制文件之一。

brew install coreutils

如果你有脚本,你更喜欢写一次(Linux + macOS)而不是两次,或者避免有If块,你需要检测操作系统,知道是否调用nproc vs sysctl -n hw。Logicalcpu,这可能是一个更好的选择。

getconf在Mac OS X和Linux上都可以工作,以防你需要它与这两个系统兼容:

$ getconf _NPROCESSORS_ONLN
12

要在C中做到这一点,你可以使用sysctl(3)函数族:

int count;
size_t count_len = sizeof(count);
sysctlbyname("hw.logicalcpu", &count, &count_len, NULL, 0);
fprintf(stderr,"you have %i cpu cores", count);

用有趣的值来代替“hw”。Logicalcpu”,用于计算内核数,是(来自内核源代码中的注释):

hw.ncpu: The maximum number of processors that could be available this boot. Use this value for sizing of static per processor arrays; i.e. processor load statistics. hw.activecpu: The number of processors currently available for executing threads. Use this number to determine the number threads to create in SMP aware applications. This number can change when power management modes are changed. hw.physicalcpu: The number of physical processors available in the current power management mode. hw.physicalcpu_max: The maximum number of physical processors that could be available this boot. hw.logicalcpu: The number of logical processors available in the current power management mode. hw.logicalcpu_max: The maximum number of logical processors that could be available this boot.