It's not the first time I write about cgroups, but a lot has changed since I wrote that post.

Not so long ago, someone mentioned in #OpenWrt that his desktop became sluggish while building an OpenWrt image. I hadn't really noticed this myself, as most of the time I am building on a remote box over SSH. However, yesterday I was physically using that machine, and I did notice lag while abusing the CPU. I wasn't building an OpenWrt image, but that doesn't really matter. Whether you're building an OpenWrt image, running emerge @world or mining some cryptocurrency, if your desktop is lagging when your CPU usage is near 100%, you can improve the situation with cgroups. In this example I will use portage as the CPU hog.

In the past I have used libcgroup to configure the control groups, but today I am going to create a slice with systemd. For this, I've created a file in /etc/systemd/system/portage.slice:



The settings you can use in the Slice section can be found here. The CPUShares option defaults to 1024. As systemd will create a user slice for each user with an active session, and all tasks that user executes will be assigned to that slice, anything I run will receive 4 times the CPU bandwidth of processes assigned to the portage slice.

Activate the slice:

systemctl start portage.slice

Now all that is left, is to assign the emerge process to the portage slice. For this, we can abuse the PORTAGE_IONICE_COMMAND option in make.conf:

PORTAGE_IONICE_COMMAND="/usr/local/sbin/ \${PID}" <br />

This will pass the PID of the emerge process to the script, which in turn will register the PID in the portage slice:


for f in $(ls /sys/fs/cgroup/*/portage.slice/tasks); do
        echo "${1}" &gt; "${f}"

From now on, all child processes of emerge will also be assigned to the slice.

A quick test shows the expected results. When only emerge is running, the portage slice uses up to 1200% CPU (12 threads at 100%). If I start openssl speed -multi 12 as my user, the CPU usage of the portage slice drops to ~240%, my user gets the other 960%, and the desktop lag is gone. Woooot!