使用golang获取CPU使用率 [英] Getting CPU usage with golang

查看:8799
本文介绍了使用golang获取CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

My Go程序需要知道所有系统和用户进程的当前cpu使用百分比。



如何获取?

解决方案

我有类似的问题,从来没有找到轻量级的实现。这是我的解决方案的简化版本,可以解答您的具体问题。我像tylerl推荐的那样对 / proc / stat 文件进行了抽样。您会注意到我在样本间等待了3秒钟以匹配顶部的输出,但我也有1秒或2秒的良好结果。我在去程序的循环中运行类似的代码,然后当我从其他去程序需要它时访问CPU使用情况。

您也可以解析的输出top -n1 | grep -i cpu 来获得CPU使用率,但它只在我的Linux机器上采样了半秒钟,并且在重负载时它已经关闭了。当我同步它和下面的程序时,常规顶部似乎非常紧密匹配:

 包主

导入(
fmt
io / ioutil
strconv
字符串
时间


func getCPUSample()(idle,total uint64){
contents,err:= ioutil.ReadFile(/ proc / stat)
if err!= nil {
return

$ b lines:= strings.Split(string(contents),\\\

for _,line:= range(lines){
fields:= strings.Fields (行)
if [0] ==cpu{
numFields:= len(fields)
for i:= 1;我< numFields; i ++ {
val,err:= strconv.ParseUint(fields [i],10,64)
if err!= nil {
fmt.Println(Error:,i,fields [i],err)
}
total + = val //计算所有数字以获得总滴答数
if i == 4 {// idle是CPU中的第5个字段行
空闲= val
}
}
返回
}
}
返回
}

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使用率为%f %% [busy:%f,total:%f] \ n,cpuUsage,totalTicks-idleTicks,totalTicks)
}

好像我是个a被放到链接到我在bitbucket上写的完整实现上;如果不是,请随时删除。目前为止,它只能在linux上运行: systemstat.go


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

How can I obtain that?

解决方案

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), "\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
}

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]\n", 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

这篇关于使用golang获取CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆