获取 linux 的 CPU 使用率

linux CPU 用量保存在 /proc/stat 文件里。
4.4 内核已经拓展到十元组,通过

man proc

可以知道分别时是 user nice system idle iowait irq softirq steal guest guest_nice

go 实现

package main

import (
    "encoding/binary"
    "fmt"
    "os"
    "time"
)

var fstat *os.File

func getcpuusage() (int, int) {
    fd := fstat
    if fd == nil {
        var err error
        fd, err = os.Open("/proc/stat")
        if err != nil {
            return -1, -1
        }
        fstat = fd
    }
    var stat [128]byte
    fd.Seek(0, os.SEEK_SET)
    n, err := fd.Read(stat[:])
    if fd != fstat {
        fd.Close()
    }
    if err != nil || binary.LittleEndian.Uint32(stat[:4]) != 0x20757063 {
        return -1, -1
    }
    total := 0
    idle := 0
    usage := 0
    idx := 0
    ok := false
    eol := false
    for i := 4; i < n; i++ {
        c := stat[i]
        if c == '\n' {
            total += usage
            eol = true
            break
        }
        if '0' <= c && c <= '9' {
            usage *= 10
            usage += int(c) - '0'
            ok = true
        } else if ok {
            total += usage
            if idx == 3 {
                idle = usage
            }
            usage = 0
            idx++
            ok = false
        }
    }
    if !eol {
        return -1, -1
    }
    return total, idle
}

func main() {
    prevtotal, previdle := 0, 0
    for {
        total, idle := getcpuusage()
        usage := 100 - 100*(idle-previdle)/(total-prevtotal+1)
        fmt.Println(usage)
        prevtotal, previdle = total, idle
        time.Sleep(time.Second)
    }
}

标签: go, linux

添加新评论