Skip to content

Instantly share code, notes, and snippets.

@alexmozaidze
Last active January 24, 2026 08:28
Show Gist options
  • Select an option

  • Save alexmozaidze/36ed00e2c74d57a5cec430a9c4792aac to your computer and use it in GitHub Desktop.

Select an option

Save alexmozaidze/36ed00e2c74d57a5cec430a9c4792aac to your computer and use it in GitHub Desktop.
Shell script for checking GPU's average usage
#!/usr/bin/env bash
is_number() {
[[ $1 =~ ^([0-9]+|[0-9]+\.[0-9]*|\.[0-9]+)$ ]]
}
is_integer() {
[[ $1 =~ ^[0-9]+$ ]]
}
echo_error() {
>&2 echo "Error: $*"
}
error() {
echo_error "$@"
exit 1
}
is_valid_gpu_usage_file() {
local file_path
file_path="$1"
if ! [[ -r $file_path ]]; then
echo_error $'Provided GPU path is not readable or doesn\'t exist'
return 1
fi
local file_contents
file_contents="$(< "$file_path")"
if [[ -z $file_contents ]]; then
echo_error 'Provided GPU file is empty'
return 1
fi
if [[ $file_contents == *$'\n'* ]]; then
echo_error "Provided GPU path doesn't yield the expected output: file must contain only 1 line"
return 1
fi
if ! is_number "$file_contents"; then
echo_error $'Provided GPU path doesn\'t yield the expected output: file must always contain a number'
return 1
fi
}
should_truncate=false
sampling_duration=1
samples_amount=10
gpu_usage_path=
while getopts 'td:s:g:' flag; do
case "${flag}" in
t) should_truncate=true ;;
d)
if ! is_number "$OPTARG"; then
error "Sampling interval must be a number (float or integer)"
fi
sampling_duration="$OPTARG"
;;
s)
if ! is_integer "$OPTARG"; then
error "Samples amount must be an integer"
fi
samples_amount="$OPTARG"
;;
g)
if ! is_valid_gpu_usage_file "$OPTARG"; then
error "Invalid GPU usage file"
fi
gpu_usage_path="$OPTARG"
;;
*) error "Invalid argument: $flag"
esac
done
if [[ -z $gpu_usage_path ]]; then
error 'GPU usage file path is unspecified. Specify the path using the -g flag'
fi
sleep_duration="$(bc <<< "scale=4; $sampling_duration/$samples_amount")"
average="$(
for (( i=0; i < samples_amount; i++ )); do
echo "$(< "$gpu_usage_path")"
sleep "$sleep_duration"
done | awk '{sum+=$1} END {print sum/NR}'
)"
if $should_truncate; then
average="${average%.*}"
fi
echo "$average"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment