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.
CLARIFICATION
When this question was asked the OP did not say that he wanted the number of LOGICAL cores rather than the actual number of cores, so this answer logically (no pun intended) answers with a way to get the actual number of real physical cores, not the number that the OS tries to virtualize through hyperthreading voodoo.
UPDATE TO HANDLE FLAW IN YOSEMITE
Due to a weird bug in OS X Yosemite (and possibly newer versions, such as the upcoming El Capitan), I've made a small modification. (The old version still worked perfectly well if you just ignore STDERR, which is all the modification does for you.)
Every other answer given here either
bundle install --jobs 3
where you want the number in place of3
to be one less than the number of cores you've got, or at least not more than the number of cores)The way to get just the number of cores, reliably, correctly, reasonably quickly, and without extra information or even extra characters around the answer, is this:
As jkp said in a comment, that doesn't show the actual number of physical cores. to get the number of physical cores you can use the following command:
This should be cross platform. At least for Linux and Mac OS X.
A little bit slow but works.
To do this in C you can use the sysctl(3) family of functions:
Interesting values to use in place of "hw.logicalcpu", which counts cores, are:
On a MacBook Pro running Mavericks,
sysctl -a | grep hw.cpu
will only return some cryptic details. Much more detailed and accessible information is revealed in themachdep.cpu
section, ie:In particular, for processors with
HyperThreading
(HT), you'll see the total enumerated CPU count (logical_per_package
) as double that of the physical core count (cores_per_package
).