--- /dev/null
+#! /bin/sh
+
+proc_stat_parse() {
+ proc_stat="$1"
+ n='[0-9]\+'
+ echo "$proc_stat" \
+ | grep "^cpu$n $n $n $n $n $n $n $n $n $n $n$" \
+ | awk '
+ {
+ cpu = $1;
+ user = $2;
+ sys = $4;
+ idle = $5;
+
+ total = user + sys + idle;
+ busy = user + sys;
+
+ if (NR > 1) {printf " "};
+
+ out = sprintf("%s %d %d", cpu, total, busy);
+ #print out >> "cpu_usage_debug.txt";
+ printf "%s", out;
+ }
+ END {
+ #print "" >> "cpu_usage_debug.txt";
+ print "";
+ }
+ '
+}
+
+calc_delta() {
+ for proc_stat in "$1" "$2"; do
+ proc_stat_parse "$proc_stat"
+ done \
+ | awk '
+ {
+ t = NR;
+ for (i = 1; i <= (NF - 2); i += 3) {
+ cpu_count[t]++;
+ cpu_id = $i; # For occasional debugging
+ total = $(i + 1);
+ busy = $(i + 2);
+ cpu[cpu_count[t], "total", t] = total;
+ cpu[cpu_count[t], "busy" , t] = busy;
+ }
+ }
+
+ END {
+ for (c=1; c<=cpu_count[2]; c++) {
+ total_1 = cpu[c, "total", 1];
+ total_2 = cpu[c, "total", 2];
+ busy_1 = cpu[c, "busy" , 1];
+ busy_2 = cpu[c, "busy" , 2];
+ total_d = total_2 - total_1;
+ busy_d = busy_2 - busy_1;
+ percent_busy = (busy_d / total_d) * 100;
+
+ #printf(\
+ # "c: %d, total_1: %f total_2: %f, total_d: %f\n",
+ # c, total_1, total_2, total_d \
+ #) >> "cpu_usage_debug.txt";
+ #printf(\
+ # "c: %d, busy_1: %f busy_2: %f, busy_d: %f\n",
+ # c, busy_1, busy_2, busy_d \
+ #) >> "cpu_usage_debug.txt";
+ #printf(\
+ # "c: %d, percent_busy: %f\n",
+ # c, percent_busy \
+ #) >> "cpu_usage_debug.txt";
+
+ if (c > 1) {printf " "};
+ out = sprintf("%3.0f%%", percent_busy)
+ #printf "c: %d, out: %s\n", c, out >> "cpu_usage_debug.txt";
+ printf "%s", out;
+ }
+ #print "" >> "cpu_usage_debug.txt";
+ print "";
+ }
+ '
+}
+
+main() {
+ last_proc_stat="$HOME/var/run/cpu_usage_from_proc_since_last_check/last_proc_stat"
+
+ if [ ! -f "$last_proc_stat" ]
+ then
+ mkdir -p `dirname "$last_proc_stat"`
+ cat /proc/stat > "$last_proc_stat"
+ sleep 0.1
+ fi
+
+ previous=`cat $last_proc_stat`;
+ cat /proc/stat > "$last_proc_stat"
+ current=`cat $last_proc_stat`;
+
+ calc_delta "$previous" "$current"
+}
+
+main $@