Skip to content

Instantly share code, notes, and snippets.

@optilude
Created March 15, 2020 20:09
Show Gist options
  • Save optilude/129bf7d20bb39a4a1aa596ca4c1d6afb to your computer and use it in GitHub Desktop.
Save optilude/129bf7d20bb39a4a1aa596ca4c1d6afb to your computer and use it in GitHub Desktop.
Capture processes with significant CPU usage (Bash shell script)
#!/bin/bash
# Output CSV-formatted statistics about each process using > ${threshold}% CPU,
# sampling every ${delay} seconds. Assume we'll find them in the top ${max}
# processes returned by `top` sorting by CPU usage.
threshold=${1:-5}
delay=${2:-5}
max=${3:-25}
echo "Threshold: ${threshold}% CPU. Sampling every ${delay} seconds." > /dev/stderr
echo "Timestamp,Process,CPU"
while True
do
ps aux -c -r | tail -n +2 | head -n ${max} | while read -r line
do
cpu=$(echo "${line}" | awk '{print $3}')
process=$(echo "${line}" | awk '{print $11}')
timestamp=$(date +"%Y-%m-%d %H:%M:%S")
if (( $(echo "${cpu} >= ${threshold}" | bc -l) ))
then
echo "${timestamp},${process},${cpu}"
fi
done
echo "." > /dev/stderr
sleep ${delay}
done
@optilude
Copy link
Author

optilude commented Mar 15, 2020

Save it as e.g. find-cpu-hogs.sh and run chmod +x find-cpu-hogs.sh in a terminal to make it executable.

Run as:

$ ./find-cpu-hogs.sh | tee cpu-hogs.csv

This will output all processes using more than 5% CPU, sampling every 5 seconds, to a CSV file, which you can then analyse in Excel, say. It will write a . to the console (stderr) but not the file (assuming you use tee as above) each time it samples so you know it’s doing something even if no processes go over the threshold.

Use CTRL+C to stop it.

If you run it again, it will overwrite the CSV file. You can use the -a argument to tee to append instead (though you’ll get the header twice so you’ll need to clean up the file a bit later).

You can change the threshold and frequency by passing one or two command line arguments, e.g.:

$ ./find-cpu-hogs.sh 10 20 | tee -cpu-hogs.csv

This will put the threshold at 10% and sample every 20 seconds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment