Created
March 15, 2020 20:09
-
-
Save optilude/129bf7d20bb39a4a1aa596ca4c1d6afb to your computer and use it in GitHub Desktop.
Capture processes with significant CPU usage (Bash shell script)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Save it as e.g.
find-cpu-hogs.sh
and runchmod +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 totee
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.