当你运行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。
执行system_profiler | grep "Cores"命令。
我有一个:
MacBook Pro Retina, 2012年年中。
处理器:2.6 GHz英特尔酷睿i7
user$ system_profiler | grep "Cores"
Total Number of Cores: 4
user$ sysctl -n hw.ncpu
8
根据维基百科(http://en.wikipedia.org/wiki/Intel_Core#Core_i7),没有8个物理核的Core i7,所以超线程的想法肯定是这样的。忽略sysctl,使用system_profiler值以保证准确性。真正的问题是,您是否能够有效地运行具有4核的应用程序(长编译作业?)而不中断其他进程。
运行4核并行编译器似乎不会显著影响常规操作系统。所以,把它当作8核来处理也不是那么糟糕。
要在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.