@@ -12,27 +12,12 @@ import (
1212 "time"
1313)
1414
15- // cpuUsage samples /proc/stat twice 100ms apart and returns the ratio 0.0–1.0.
16- func cpuUsage () (float64 , error ) {
17- s1 , err := readCPUStat ()
18- if err != nil {
19- return 0 , err
20- }
21- time .Sleep (100 * time .Millisecond )
22- s2 , err := readCPUStat ()
23- if err != nil {
24- return 0 , err
25- }
26- total := float64 (s2 .total - s1 .total )
27- idle := float64 (s2 .idle - s1 .idle )
28- if total == 0 {
29- return 0 , nil
30- }
31- return (total - idle ) / total , nil
15+ type cpuStat struct {
16+ total uint64
17+ idle uint64
18+ iowait uint64
3219}
3320
34- type cpuStat struct { total , idle uint64 }
35-
3621func readCPUStat () (cpuStat , error ) {
3722 f , err := os .Open ("/proc/stat" )
3823 if err != nil {
@@ -59,11 +44,38 @@ func readCPUStat() (cpuStat, error) {
5944 if len (vals ) > 3 {
6045 idle = vals [3 ]
6146 }
62- return cpuStat {total : total , idle : idle }, nil
47+ iowait := uint64 (0 )
48+ if len (vals ) > 4 {
49+ iowait = vals [4 ]
50+ }
51+ return cpuStat {total : total , idle : idle , iowait : iowait }, nil
6352 }
6453 return cpuStat {}, fmt .Errorf ("cpu line not found in /proc/stat" )
6554}
6655
56+ // cpuAndIOWaitUsage samples /proc/stat twice 100ms apart and returns both
57+ // the CPU usage ratio and the iowait ratio (both 0.0–1.0).
58+ func cpuAndIOWaitUsage () (cpuRatio , iowaitRatio float64 , err error ) {
59+ s1 , err := readCPUStat ()
60+ if err != nil {
61+ return
62+ }
63+ time .Sleep (100 * time .Millisecond )
64+ s2 , err := readCPUStat ()
65+ if err != nil {
66+ return
67+ }
68+ total := float64 (s2 .total - s1 .total )
69+ if total == 0 {
70+ return
71+ }
72+ idle := float64 (s2 .idle - s1 .idle )
73+ iowait := float64 (s2 .iowait - s1 .iowait )
74+ cpuRatio = (total - idle ) / total
75+ iowaitRatio = iowait / total
76+ return
77+ }
78+
6779// memUsedBytes returns MemTotal - MemAvailable from /proc/meminfo.
6880func memUsedBytes () (int64 , error ) {
6981 f , err := os .Open ("/proc/meminfo" )
0 commit comments