vineri, 6 noiembrie 2009

Detect number of CPUs on a machine

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

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

[cc lang="bash"]
grep -c processor /proc/cpuinfo
[/cc]

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:

[cc lang="make"]
#...
CORES := $(shell grep -c processor /proc/cpuinfo)
#...
make -j$(CORES)
#...
[/cc]

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

[cc lang="bash"]
make -j`grep -c processor /proc/cpuinfo`
[/cc]

Un comentariu: