How many physical cores on Linux

by Carson Reynolds

Suppose you want to write a script which parallelizes building a large program. You could just assume that everyone has dual-core, but that would saturate a single core and under-utilize a hex core. A smarter method would be to set N in make’s -jN to be proportional to the number of physical cores in your computer. Over at how-to geek there is a script which gets close. However, when you have a hyperthreaded processor, their technique will over-report the number of actual cores. Here is a slightly more complex script which will extract the number of cores from cpuinfo:

grep "$cpu cores" /proc/cpuinfo | head -n 1 | cut -d ' ' -f 3

If you execute this on a Core i7 the script finds the actual number of physical cores:

$ grep "$cpu cores" /proc/cpuinfo | head -n 1 | cut -d ' ' -f 3