How to discover number of *logical* cores on Mac OS X?

How can you tell, from the command line, how many cores are on the machine when you're running Mac OS X? On Linux, I use:

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

It's not perfect, but it's close. This is intended to get fed to make, which is why it gives a result 1 higher than the actual number. And I know the above code can be written denser in Perl or can be written using grep, wc, and cut, but I decided the above was a good tradeoff between conciseness and readability.

VERY LATE EDIT: Just to clarify: I'm asking how many logical cores are available, because this corresponds with how many simultaneous jobs I want make to spawn. jkp's answer, further refined by Chris Lloyd, was exactly what I needed. YMMV.


Solution 1:

You can do this using the sysctl utility:

sysctl -n hw.ncpu

Solution 2:

Even easier:

sysctl -n hw.ncpu

Solution 3:

This should be cross platform. At least for Linux and Mac OS X.

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

A little bit slow but works.

Solution 4:

system_profiler SPHardwareDataType shows I have 1 processor and 4 cores.

[~] system_profiler SPHardwareDataType
Hardware:

    Hardware Overview:

      Model Name: MacBook Pro
      Model Identifier: MacBookPro9,1
      Processor Name: Intel Core i7
      Processor Speed: 2.6 GHz
      Number of Processors: 1
      Total Number of Cores: 4

      <snip>

[~] 

However, sysctl disagrees:

[~] sysctl -n hw.logicalcpu
8
[~] sysctl -n hw.physicalcpu
4
[~] 

But sysctl appears correct, as when I run a program that should take up all CPU slots, I see this program taking close to 800% of CPU time (in top):

PID   COMMAND      %CPU  
4306  top          5.6   
4304  java         745.7 
4296  locationd    0.0  

Solution 5:

To do this in C you can use the sysctl(3) family of functions:

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

Interesting values to use in place of "hw.logicalcpu", which counts cores, are (from this comment in the kernel source):

  • 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.