douhuibo5635 2012-07-06 05:30
浏览 1124
已采纳

使用golang获取CPU使用率

My Go program needs to know the current cpu usage percentage of all system and user processes.

How can I obtain that?

  • 写回答

6条回答 默认 最新

  • dsmvqp3124 2013-07-22 09:12
    关注

    I had a similar issue and never found a lightweight implementation. Here is a slimmed down version of my solution that answers your specific question. I sample the /proc/stat file just like tylerl recommends. You'll notice that I wait 3 seconds between samples to match top's output, but I have also had good results with 1 or 2 seconds. I run similar code in a loop within a go routine, then I access the cpu usage when I need it from other go routines.

    You can also parse the output of top -n1 | grep -i cpu to get the cpu usage, but it only samples for half a second on my linux box and it was way off during heavy load. Regular top seemed to match very closely when I synchronized it and the following program:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "strconv"
        "strings"
        "time"
    )
    
    func getCPUSample() (idle, total uint64) {
        contents, err := ioutil.ReadFile("/proc/stat")
        if err != nil {
            return
        }
        lines := strings.Split(string(contents), "
    ")
        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
    }
    
    func main() {
        idle0, total0 := getCPUSample()
        time.Sleep(3 * time.Second)
        idle1, total1 := getCPUSample()
    
        idleTicks := float64(idle1 - idle0)
        totalTicks := float64(total1 - total0)
        cpuUsage := 100 * (totalTicks - idleTicks) / totalTicks
    
        fmt.Printf("CPU usage is %f%% [busy: %f, total: %f]
    ", cpuUsage, totalTicks-idleTicks, totalTicks)
    }
    

    It seems like I'm allowed to link to the full implementation that I wrote on bitbucket; if it's not, feel free to delete this. It only works on linux so far, though: systemstat.go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器