Skip to content

Instantly share code, notes, and snippets.

@hlorand
Created August 16, 2015 23:31
Show Gist options
  • Save hlorand/da21ef5d5492f2556a5f to your computer and use it in GitHub Desktop.
Save hlorand/da21ef5d5492f2556a5f to your computer and use it in GitHub Desktop.
Script that limits application CPU usage on OSX
#!/bin/bash
#########################
# CPU LIMITER (for OSX) #
#########################
<<DESCRIPTION
The script limits an application CPU usage.
-------------------------------------------
You have to specify application PID (process id) and desired CPU usage percentage.
The script is a big while loop that
(1) sends SIGSTOP signal to the appication
(2) sleeps X millisecond
(3) sends SIGCONT signal.
Sleeping time gets bigger ( X += 0.01 ) when actual CPU usage is over the limit
Sleeping time gets smaller ( X -= 0.005) when actual CPU usage is under the limit
This way the average CPU usage hovers around the desired percentage.
DESCRIPTION
<<USAGE
(1) sudo chmod +x cpu_limiter.sh
(2) Run 'top' from terminal to see application PIDs
Script works with 2 parameter:
- pid of the application what you want to limit
- cpu usage limit in percents (0-100)
Example
cpu_limiter.sh 1234 20
This limits the application with 1234 PID to 20% CPU
USAGE
<<CREATOR
Lorand Horvath, email at hlorand.hu, 2015
CREATOR
###########################################################################################
# PARAMETERS
PID=$1
PERCENT=$2
# INITIAL SLEEPTIME
SLEEPTIME=0
while true
do
# THE HEART OF THE SCRIPT
# -----------------------
kill -SIGSTOP $PID &
sleep $SLEEPTIME
kill -SIGCONT $PID &
# CPU USAGE OF THE APPLICATION
# ----------------------------
# ps prints only the cpu% of the app, tail gets only the last line
# tr and awk filters out comma and space to get integer part
CPUUSAGE=$(ps -p $PID -o %cpu | tail -1 | tr -d ' ' | tr ',' ' ' | awk '{print $1}')
#CPUUSAGE=$(ps -p $PID -o %cpu | tail -1 | tr -d ' ' | tr ',' '.')
#DIFFERENCE=$( echo '(' $CPUUSAGE '-' $PERCENT ') / 1000' | bc -l )
# CALIBRATING SLEEP TIME
# ----------------------
# If actual CPU usage is smaller than the limit, slowly decrease sleep time
if [ $( echo $CPUUSAGE '<' $PERCENT | bc ) -eq 1 ]; then
if [ $( echo $SLEEPTIME '<0.00001' | bc ) -eq 0 ]; then
SLEEPTIME=$( echo $SLEEPTIME ' - 0.005' | bc -l)
fi
fi
# If actual CPU usage is bigger than the limit, increase sleep time
if [ $( echo $CPUUSAGE '>' $PERCENT | bc ) -eq 1 ]; then
if [ $( echo $SLEEPTIME '>0.5' | bc ) -eq 0 ]; then
SLEEPTIME=$( echo $SLEEPTIME ' + 0.01' | bc -l)
fi
fi
# debug info
echo $SLEEPTIME $CPUUSAGE
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment