Created
May 15, 2021 21:12
-
-
Save Sangdol/168b3a687b2becc2f74d1d5a5f7670f5 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env bash | |
# | |
# Threadhold 값 (30%) 이상 CPU 점유하고 있는 프로세스 중 가장 높은 CPU 점유하고 있는 프로세스 반환합니다. | |
# Better Touch Tool과 연동하여 TaskBar에 노출시키기 위해 사용하거나 | |
# TextBar http://richsomerfield.com/apps/textbar/ 와 함께 사용할 수 있습니다. | |
# 5초에 한번 정도 실행하도록 설정하면 적당합니다. | |
# | |
# https://stackoverflow.com/questions/24129903/notifying-when-using-high-cpu-via-applescript-or-automator | |
SAMPLE_SIZE=2 | |
DELAY_SECS=1 | |
TOP_APP_NUM=10 # number of apps to sum up | |
CPU_THRESHOLD=30 | |
# Check out this gist to understand what's going on | |
# https://gist.github.com/Sangdol/0a5f1125a5b3bd67ed1562c50bb7f451 | |
# | |
# -l: samples / increase the number to ignore the first result which has 0% cpu. | |
# -s: deplay-secs | |
# -n: number of processes | |
# -F: Do not calculate statistics on shared libraries, also known as frameworks. | |
# -o: order by (desc) | |
# -stats: display keys | |
read -r name pct < <(/usr/bin/top -s $DELAY_SECS -l $((SAMPLE_SIZE + 1)) -n $TOP_APP_NUM -F -o cpu -stats cpu,pid,command | \ | |
# Select results after the header that has %CPU | |
grep -A$TOP_APP_NUM "%CPU" | \ | |
# Delete the first block which has 0% as cpu result | |
sed '1,/^--/d' | \ | |
# Remove headers | |
grep -v "%CPU" | \ | |
# Remove borders between results | |
grep -v "^--" | \ | |
# Sum up for each app based on pid | |
# $1: cpu, $2: pid, $3, command | |
awk '{cpu[$2]+=$1;app_name[$2]=$3} END {for (pid in cpu) printf("%s\t%s\n", app_name[pid], cpu[pid])}' | \ | |
# -n: number | |
# -k: nth key | |
sort -n -k2 | \ | |
tail -1) | |
pct=$(bc -l <<< "scale=1;$pct / $SAMPLE_SIZE") | |
# For debugging | |
# echo "$name $pct" | |
if (( ${pct%.*} >= CPU_THRESHOLD )); then | |
msg="Process > $CPU_THRESHOLD%: $name ($pct%)" | |
echo "$(date +"%Y-%m-%d %H:%M") $msg" >> "/usr/local/var/log/cpu-monitor.log" | |
textbar="$name ($pct%)" | |
echo "$textbar" | |
else | |
echo "🌳" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment