Commit | Line | Data |
---|---|---|
a4ecb5bc SK |
1 | #! /bin/sh |
2 | ||
3 | proc_stat_parse() { | |
4 | proc_stat="$1" | |
5 | n='[0-9]\+' | |
6 | echo "$proc_stat" \ | |
7 | | grep "^cpu$n $n $n $n $n $n $n $n $n $n $n$" \ | |
8 | | awk ' | |
9 | { | |
10 | cpu = $1; | |
11 | user = $2; | |
12 | sys = $4; | |
13 | idle = $5; | |
14 | ||
15 | total = user + sys + idle; | |
16 | busy = user + sys; | |
17 | ||
18 | if (NR > 1) {printf " "}; | |
19 | ||
20 | out = sprintf("%s %d %d", cpu, total, busy); | |
21 | #print out >> "cpu_usage_debug.txt"; | |
22 | printf "%s", out; | |
23 | } | |
24 | END { | |
25 | #print "" >> "cpu_usage_debug.txt"; | |
26 | print ""; | |
27 | } | |
28 | ' | |
29 | } | |
30 | ||
31 | calc_delta() { | |
32 | for proc_stat in "$1" "$2"; do | |
33 | proc_stat_parse "$proc_stat" | |
34 | done \ | |
35 | | awk ' | |
36 | { | |
37 | t = NR; | |
38 | for (i = 1; i <= (NF - 2); i += 3) { | |
39 | cpu_count[t]++; | |
40 | cpu_id = $i; # For occasional debugging | |
41 | total = $(i + 1); | |
42 | busy = $(i + 2); | |
43 | cpu[cpu_count[t], "total", t] = total; | |
44 | cpu[cpu_count[t], "busy" , t] = busy; | |
45 | } | |
46 | } | |
47 | ||
48 | END { | |
49 | for (c=1; c<=cpu_count[2]; c++) { | |
50 | total_1 = cpu[c, "total", 1]; | |
51 | total_2 = cpu[c, "total", 2]; | |
52 | busy_1 = cpu[c, "busy" , 1]; | |
53 | busy_2 = cpu[c, "busy" , 2]; | |
54 | total_d = total_2 - total_1; | |
55 | busy_d = busy_2 - busy_1; | |
56 | percent_busy = (busy_d / total_d) * 100; | |
57 | ||
58 | #printf(\ | |
59 | # "c: %d, total_1: %f total_2: %f, total_d: %f\n", | |
60 | # c, total_1, total_2, total_d \ | |
61 | #) >> "cpu_usage_debug.txt"; | |
62 | #printf(\ | |
63 | # "c: %d, busy_1: %f busy_2: %f, busy_d: %f\n", | |
64 | # c, busy_1, busy_2, busy_d \ | |
65 | #) >> "cpu_usage_debug.txt"; | |
66 | #printf(\ | |
67 | # "c: %d, percent_busy: %f\n", | |
68 | # c, percent_busy \ | |
69 | #) >> "cpu_usage_debug.txt"; | |
70 | ||
71 | if (c > 1) {printf " "}; | |
72 | out = sprintf("%3.0f%%", percent_busy) | |
73 | #printf "c: %d, out: %s\n", c, out >> "cpu_usage_debug.txt"; | |
74 | printf "%s", out; | |
75 | } | |
76 | #print "" >> "cpu_usage_debug.txt"; | |
77 | print ""; | |
78 | } | |
79 | ' | |
80 | } | |
81 | ||
82 | main() { | |
83 | last_proc_stat="$HOME/var/run/cpu_usage_from_proc_since_last_check/last_proc_stat" | |
84 | ||
85 | if [ ! -f "$last_proc_stat" ] | |
86 | then | |
87 | mkdir -p `dirname "$last_proc_stat"` | |
88 | cat /proc/stat > "$last_proc_stat" | |
89 | sleep 0.1 | |
90 | fi | |
91 | ||
92 | previous=`cat $last_proc_stat`; | |
93 | cat /proc/stat > "$last_proc_stat" | |
94 | current=`cat $last_proc_stat`; | |
95 | ||
96 | calc_delta "$previous" "$current" | |
97 | } | |
98 | ||
99 | main $@ |