2 CPU Stats
tengel edited this page 2024-09-05 07:43:21 -05:00

Sample the CPU for stats while testing

#!usr/bin/env bash

DTS=$(date +"%Y%m%d")

if [[ -z "$1" ]]; then
  echo "Usage: $0 xxx"
  echo "   where xxx is the number of seconds to collect data"
  exit 1
fi

# check deps
command -v awk >/dev/null 2>&1 || {
echo " awk not installed. Aborting!" >&2; exit 1; }

command -v bc >/dev/null 2>&1 || {
echo " bc not installed. Aborting!" >&2; exit 1; }

# make sure $1 is an interger
[[ "$1" =~ ^-?[0-9]+$ ]] || {
echo " Supply an interger and try again." >&2; exit 1; }

[[ -d $XDG_RUNTIME_DIR ]] &&
file=$XDG_RUNTIME_DIR/"stats-$DTS" || file=/tmp/"stats-$DTS"

[[ -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq ]] || {
echo " Cannot tell what the CPU current CPU frequency is. Aborting!" >&2; exit 1; }

function full_exit {
  [[ ! -r "$file" ]] && exit 1
  # credit for awk magic goes to
  # http://stackoverflow.com/questions/6166375/median-of-column-with-awk
  median=$(sort -n $file | awk ' { a[i++]=$1; } END { x=int((i+1)/2); if (x < (i+1)/2) print (a[x-1]+a[x])/2; else print a[x-1]; }')
  mean=$(awk '{ sum += $1; n++ } END { if (n > 0) print sum / n; }' $file)
  min=$(sort -n $file | head -n1)
  max=$(sort -n $file | tail -n1)

  echo
  echo "All values in MHz except count which is just the number of measurements..."
  echo "median : $median"
  echo "mean   : $mean"
  echo "max    : $max"
  echo "min    : $min"
  echo "count  : $(wc -l $file|awk '{print $1}')"

  [[ -f $file ]] && rm -f $file
  exit 0
}
trap full_exit SIGHUP SIGINT SIGTERM

echo "Collecting data for $1 seconds..."
TIME=( $(seq 1 1 "$1") )

for i in "${TIME[@]}"; do
  sleep 1
  bc <<< "scale=1; $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq)/1000" >> "$file"
done

full_exit