#!/bin/bash ######## # ksm-stats # version 2023-06-09.1 # # License CC-BY-SA 4.0 # https://wiki.tnonline.net ######## # Directory containing the KSM files directory="/sys/kernel/mm/ksm/" # Get system page size in bytes page_size=$(getconf PAGESIZE) # Declare an associative array to store variables and values declare -A variables # Get a list of variable files variable_files=("$directory"/*) # Iterate over variable files for file in "${variable_files[@]}"; do # Get the variable name from the file name var=$(basename "$file") # Read the variable value from the file read -r value < "$file" # Store the variable and value in the array variables["$var"]="$value" done # Calculate the total memory used and saved by KSM in MiB memory_used=$((variables["pages_sharing"] * page_size / (1024 * 1024) )) memory_saved=$((memory_used - (variables["pages_shared"] * page_size / (1024 * 1024)) )) # Calculate the efficiency ratio if [ "${variables["pages_shared"]}" -ne 0 ]; then efficiency_ratio=$(bc <<< "scale=2; ${variables["pages_sharing"]} / ${variables["pages_shared"]}") else efficiency_ratio=0 fi # Determine the maximum length of variable names # This is used to set column widths. max_length=0 for var in "${!variables[@]}"; do if [ ${#var} -gt $max_length ]; then max_length=${#var} fi done ((width = max_length + 4)) # Iterate over variables and output their names and values printf "========\n" printf "SETTINGS" printf "\n========\n" for var in "${!variables[@]}"; do # Get the variable value from the array value=${variables["$var"]} # Output the variable name and value in columns printf "%-*s%s\n" "$width" "$var" "$value" done # Output the total memory used, memory saved and efficiency ratio. printf "\n========\n" printf "SUMMARY" printf "\n========\n" printf "%-*s%s MiB\n" "$width" "Total Memory Used by KSM:" "$memory_used" printf "%-*s%s MiB\n" "$width" "Total Memory Saved by KSM:" "$memory_saved" printf "%-*s%s\n" "$width" "Efficiency Ratio:" "$efficiency_ratio"