Gentoo : Autoconfigure number of CPU in make.conf

Ever wanted a script that just adapts make.conf to number of cpu cores.
Well, here’s my script, surely improvable but maybe useful.

It will count the number of cpu nodes.
Then make.conf gets backuped and edited accordingly.

We have 8 cpu cores, so anything like:

  • MAKEOPTS=”-j2
  • MAKEOPTS=”-j2 -l1
  • MAKEOPTS=”${MAKEOPTS} -j5 -l3.85
  • EMERGE_DEFAULT_OPTS=”${EMERGE_DEFAULT_OPTS} -j4 –load-average=3.75

becomes this:

  • MAKEOPTS=”-j9
  • MAKEOPTS=”-j9 -l7.95
  • MAKEOPTS=”${MAKEOPTS} -j9 -l7.95
  • EMERGE_DEFAULT_OPTS=”${EMERGE_DEFAULT_OPTS} -j8 –load-average=7.85

    echo "$1" 1>&2
    exit 1

# check if running as root
    if [[ $EUID -ne 0 ]]; then
       echo "This script must be run as root" 1>&2
       exit 1

# outputs number of CPU coress (with hyperthreading)
count_cpu() {
	grep -c processor /proc/cpuinfo || \
		 die "Error getting number of cpu"


# get location of make.conf
get_make() {
	if [ -e /etc/make.conf ]; then
		echo '/etc/make.conf'
	elif [ -e /etc/portage/make.conf ]; then
		echo '/etc/portage/make.conf'
		die "make.conf not found"

# create a backup of make.conf in /tmp/make.conf.backup
backup_config() {
	local dest_path='/tmp/make.conf.backup'
	local now=$(date +'%Y%m%d%I%M%S')
	echo "Creating backup of make.conf in:"
	echo "${dest_path}/make.conf.${now}"
	mkdir -p "${dest_path}" || die "mkdir ${dest_path} failed"
	cp -a "$(get_make)" "${dest_path}/make.conf.${now}" \
		|| die "cp make.conf failed"

sed_make() {
	local countC=$(count_cpu)
	sed -i -r \
		-e "s/^([[:space:]]*MAKEOPTS=.*)(["\""'[[:space:]])(-j|--jobs=)[1-9][0-9]*(["\""'[[:space:]])/\1\2\3$(($countC+1))\4/" \
		-e "s/^([[:space:]]*MAKEOPTS=.*)(["\""'[[:space:]])(-l)[1-9][0-9]*\.?[0-9]*(["\""'[[:space:]])/\1\2\3$(($countC-1))\.95\4/" \
		-e "s/^([[:space:]]*EMERGE_DEFAULT_OPTS=.*)(["\""'[[:space:]])(-j|--jobs=)[1-9][0-9]*(["\""'[[:space:]])/\1\2\3${countC}\4/" \
		-e "s/^([[:space:]]*EMERGE_DEFAULT_OPTS=.*)(["\""'[[:space:]])(--load-average=)[1-9][0-9]*\.?[0-9]*(["\""'[[:space:]])/\1\2\3$(($countC-1))\.85\4/" \
		$(get_make) || die "sed on make.conf failed"
	echo "make.conf processed for ${countC} cpu"

# sanity checks
# check at least 2 cores
[ "$(count_cpu)" -lt 2 ] && die "Less than 2 CPUs detected!"

# create backup

# modify make.conf


  1. […] Gentoo : Autoconfigure number of CPU in make.conf. […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: