The problem#
cpulimit
is a useful utility for stopping a program
from wasting CPU, but it only limits a single process. As all modern
web browsers use process isolation, limiting just
a single process doesn't do very much, we actually want to limit all of
the browser processes.
The solution#
The following script will limit the CPU usage of all browser processes
to $LIMIT
percent CPU. Note that the limit is per process not total
over all processes, so you may want to set it quite low to actually have
an effect.
LIMIT=10 # Hard-code a limit of 10% CPU as an example.
# Kill child processes (stop limiting CPU) on script exit.
for sig in INT QUIT HUP TERM; do
trap "
pkill -P $$
trap - $sig EXIT
kill -s $sig "'"$$"' "$sig"
done
trap cleanup EXIT
# Find and limit all child processes of all browsers.
for name in firefox firefox-esr chromium chrome
do
for ppid in $(pgrep "$name")
do
cpulimit --pid="$ppid" --limit="$LIMIT" &
for pid in "$ppid" $(pgrep --parent "$ppid")
do
cpulimit --pid="$pid" --limit="$LIMIT" &
done
done
done