From 7717a490dfa049ff1732fe1f6aa036a0241a122f Mon Sep 17 00:00:00 2001 From: ren yuze Date: Mon, 2 Mar 2020 17:00:24 +0800 Subject: [PATCH] add cpu monitor for linux --- os_linux.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/os_linux.go b/os_linux.go index a29a5ca..53d2c9c 100644 --- a/os_linux.go +++ b/os_linux.go @@ -3,6 +3,8 @@ package staros import ( + "fmt" + "io/ioutil" "os/user" "strconv" "strings" @@ -64,3 +66,41 @@ func Whoami() (uid, gid int, uname, gname, home string, err error) { gname = gup.Name return } + +func getCPUSample() (idle, total uint64) { + contents, err := ioutil.ReadFile("/proc/stat") + if err != nil { + return + } + lines := strings.Split(string(contents), "\n") + for _, line := range lines { + fields := strings.Fields(line) + if fields[0] == "cpu" { + numFields := len(fields) + for i := 1; i < numFields; i++ { + val, err := strconv.ParseUint(fields[i], 10, 64) + if err != nil { + fmt.Println("Error: ", i, fields[i], err) + } + total += val // tally up all the numbers to get total ticks + if i == 4 { // idle is the 5th field in the cpu line + idle = val + } + } + return + } + } + return +} + +// CpuUsage 获取CPU使用量 +func CpuUsage(sleep time.Time) float64 { + idle0, total0 := getCPUSample() + time.Sleep(sleep) + idle1, total1 := getCPUSample() + idleTicks := float64(idle1 - idle0) + totalTicks := float64(total1 - total0) + cpuUsage := 100 * (totalTicks - idleTicks) / totalTicks + return cpuUsage + //fmt.Printf("CPU usage is %f%% [busy: %f, total: %f]\n", cpuUsage, totalTicks-idleTicks, totalTicks) +}