Skip to content

Instantly share code, notes, and snippets.

@insilications
Created July 13, 2024 14:13
Show Gist options
  • Save insilications/781f4df3a3edb2f30e6f423772722bef to your computer and use it in GitHub Desktop.
Save insilications/781f4df3a3edb2f30e6f423772722bef to your computer and use it in GitHub Desktop.
Show Transparent HugePage (THP) across processes sorted by usage
#!/usr/bin/env bash
set -eu
usage_error() { echo >&2 "$(basename "$0"): $1"; exit 2; }
show_options() {
cat << 'EOF'
Show Transparent HugePage (THP) across processes sorted by usage
Usage: hptop [OPTIONS]
Options:
-h / --help - Show this help
-f / --full - Show full command line of the processes
-t [n] / --top [n] - Show top [n] processes by THP usage
EOF
}
full=0
top=0
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help) show_options; exit 0 ;;
-f|--full) full=1 ;;
-t|--top) top="${2:-0}"; shift ;;
*) usage_error "Unknown option: $1" ;;
esac
shift
done
tmp_file=$(mktemp)
trap 'rm -f "$tmp_file"' EXIT
# Use parallel processing for THP usage calculation
# shellcheck disable=SC2016
find /proc -maxdepth 1 -regex '/proc/[0-9]+' -printf '%P\n' | xargs -P "$(nproc)" -I {} bash -c '
thp=$(awk "/AnonHugePages/ {sum+=\$2} END {print sum}" /proc/{}/smaps 2>/dev/null)
[[ -n "$thp" && "$thp" -gt 0 ]] && echo "$thp {}"
' | sort -rn > "${tmp_file}"
[[ ${top} -gt 0 ]] && sed -i "$((top+1)),\$d" "${tmp_file}"
if ((full)); then
printf "%-10s %-10s %-10s %-15s %-40s %s\n" "PID" "THP (kB)" "UID" "START_TIME" "PROCESS_NAME" "COMMAND"
format='%-10s %-10s %-10s %-15s %-40s %s\n'
else
printf "%-10s %-10s %-10s %-15s %s\n" "PID" "THP (kB)" "UID" "START_TIME" "PROCESS_NAME"
format='%-10s %-10s %-10s %-15s %s\n'
fi
while read -r thp_usage pid; do
[[ -d "/proc/${pid}" ]] || continue
read -r ps_output < <(sudo ps -o pid=,uid=,start_time=,cmd= -p "${pid}" 2>/dev/null)
[[ -z "${ps_output}" ]] && continue
if ((full)); then
read -r _ uid start_time process_name cmdline <<< "${ps_output}"
# shellcheck disable=SC2059
printf "${format}" "${pid}" "${thp_usage}" "${uid}" "${start_time}" "${process_name}" "${cmdline}"
else
read -r _ uid start_time process_name _ <<< "${ps_output}"
# shellcheck disable=SC2059
printf "${format}" "${pid}" "${thp_usage}" "${uid}" "${start_time}" "${process_name}"
fi
done < "${tmp_file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment