当你运行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。


当前回答

以上2个好的回复:

1)关于接受jkp: hw的回复(和意见)。Ncpu显然已被弃用,而支持hw。logicalcpu (https://ghc.haskell.org/trac/ghc/ticket/8594)

2)关于Karl Ehr的2014年更新:在我的电脑上(2.5 ghz英特尔酷睿i7),sysctl -a | grep machdep。CPU | grep per_package返回不同的数字:

machdep.cpu。logical_per_package: 16

machdep.cpu。cores_per_package: 8

需要的值为:

machdep.cpu。core_count: 4

machdep.cpu。thread_count: 8

匹配:

hw.physicalcpu: 4

hw.logicalcpu: 8

其他回答

更简单:

sysctl -n hw.ncpu

要在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.

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

$ getconf _NPROCESSORS_ONLN
12

这应该是跨平台的。至少在Linux和Mac OS X上是这样。

python -c 'import multiprocessing as mp; print(mp.cpu_count())'

虽然有点慢,但还是有用的。

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

system_profiler SPHardwareDataType