vpalos.com // milk, cookies, segfaults…

Detect number of CPUs on a machine

by Valeriu Paloş on November 6, 2009

UPDATE: Steven pointed out (very nicely) that there’s no need for cat in this picture, grep would do just fine on its own. So, thanks Steven!

Detect how many CPU cores are present on the running machine:

grep -c processor /proc/cpuinfo

This can be very useful when writing multi-threaded programs to properly match the number of threads with the number of CPU cores.

Another very useful application is within makefiles since the make utility is capable of multi-threaded compilation using the -j option:

CORES := $(shell grep -c processor /proc/cpuinfo)
make -j$(CORES)

Or simply when running make at the command line, use:

make -j`grep -c processor /proc/cpuinfo`

2 thoughts on “Detect number of CPUs on a machine

  1. valeriup says:

    Good thinking, thanks!

  2. Steven says:

    Thanks for the tip, but no need to ‘cat’.

    grep -c '^processor' /proc/cpuinfo

Don't keep it to yourself!...