Skip to content

Instantly share code, notes, and snippets.

@treddy73
Last active July 5, 2025 22:13
Show Gist options
  • Save treddy73/228bc6eb60431eca06d9c2e133c61cb3 to your computer and use it in GitHub Desktop.
Save treddy73/228bc6eb60431eca06d9c2e133c61cb3 to your computer and use it in GitHub Desktop.
Monitor CPU function
# This function will periodically print cpu information about the given process name
# Place it in your .zshrc or equivalent file or modify it to run via #!/bin/zsh
#
# Usage: monitor_cpu mediaanalysisd 28800 5 > ~/Desktop/cpu_log.txt
# Monitors processes containing "mediaanalysisd" for 12 hours reporting every 5 seconds
#
# Run this to output statistics:
# cat ~/Desktop/cpu_log.txt | grep "mediaanalysisd " | grep -v "0.0" | awk '{sum += $NF; count++} END {if (count > 0) {print sum / count; print count;} else print "No data"}'
function monitor_cpu() {
local process_name=$1
local max_seconds=$2
local sleep_interval=$3
if [[ -z "$process_name" || -z "$max_seconds" || -z "$sleep_interval" ]]; then
echo "Usage: monitor_cpu <process_name> <max_seconds_to_run> <seconds_to_sleep_between_runs>"
return 1
fi
local iterations=$((max_seconds / sleep_interval))
if (( iterations < 1)); then
iterations=1
fi
echo "Monitoring CPU usage for process: ${process_name}"
echo "Max duration: ${max_seconds}s, Sleep interval: ${sleep_interval}s"
echo "Iterations: ${iterations}"
for i in {1..${iterations}}; do
local current_time=$(date -Iseconds)
local matched_processes=$(ps -Ao user,pid,%cpu,%mem,comm | grep "${process_name}")
if [[ -n "${matched_processes}" ]]; then
echo "${matched_processes}" | while read -r line; do
local cpu=$(echo "${line}" | awk '{print $3}')
local full_path=$(echo "${line}" | awk '{print $5}')
local base_name=$(basename "${full_path}")
echo "${current_time} ${base_name} ${cpu}"
done
else
echo "${current_time}"
fi
if (( i < iterations )); then
sleep "${sleep_interval}"
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment