Skip to content

Instantly share code, notes, and snippets.

@hgross
Forked from golimpio/egos_throttle.sh
Last active February 27, 2020 06:56
Show Gist options
  • Save hgross/4cd358d828711c97ffb1dae2b09c4512 to your computer and use it in GitHub Desktop.
Save hgross/4cd358d828711c97ffb1dae2b09c4512 to your computer and use it in GitHub Desktop.
Run cputhrottle for a list of applications in order to limit their CPU usage.
#!/bin/bash
# requires cputhrottle and pidof
# $ sudo port intall cputhrottle pidof
# or
# $ brew install cputhrottle pidof
# Run cputhrottle for a list of applications in order to limit their CPU usage.
# This script needs `pidof` and `cputhrottle` installed, which can be installed from homebrew.
# NOTE: This script was tested on MacOS only.
if [[ $EUID > 0 ]]; then
echo "Please run this script as root/sudo"
exit 1
fi
# Pass --kill as argument to kill all running cputhrottles
if [ "$1" == "--kill" ]; then
echo "Looking for running cputhrottles..."
pids=`pidof cputhrottle`
for pid in ${pids}; do
echo "> Killing PID ${pid}"
sudo kill ${pid}
done
printf "Done!\n\n"
exit 0
fi
# Start cputhrottle if it's not running yet for the given PID
set_cpu_limit() {
pid=$1
cpu_limit=$2
if [[ "$pid" == "" || "$cpu_limit" == "" || $cpu_limit -lt 1 || $cpu_limit -gt 100 ]]; then
echo "! Invalid arguments: pid=$pid, cpu_limit=$cpu_limit"
return
fi
printf "> PID=${pid}, CPU=${cpu_limit}"
service_cpu=$(ps aux | grep "sudo cputhrottle $pid $cpu_limit" | grep -v grep | wc -l)
if [[ ! $service_cpu -gt 0 ]]; then
sudo cputhrottle $pid $cpu_limit &
printf "\n"
else
printf " [already running]\n"
fi
}
declare -a applications
# Syntax='application-name;max-cpu%(1-100)'
#applications[0]='Chrome;50'
#applications[1]='idea;65'
#applications[2]='pycharm;40'
#applications[3]='webstorm;40'
#applications[4]='datagrip;40'
applications[0]='SymDaemon;1'
for i in "${applications[@]}"; do
app=(${i//;/ })
app_name=${app[0]}
cpu_limit=${app[1]}
printf "\nLooking for ${app_name}...\n"
pids=`pidof ${app}`
for pid in ${pids}; do
set_cpu_limit ${pid} ${cpu_limit}
done
done
printf "\nDone!\n"
printf "Run this script passing '--kill' as argument to remove all cputhrottles.\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment