当你运行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.
要在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.