How to get CPU usage

前端 未结 6 1834
刺人心
刺人心 2020-12-22 23:55

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

How can I obtain that?

6条回答
  •  天命终不由人
    2020-12-23 00:30

    You can use the os.exec package to execute the ps command and get the result.

    Here is a program issuing the ps aux command, parsing the result and printing the CPU usage of all processes on linux :

    package main
    
    import (
        "bytes"
        "log"
        "os/exec"
        "strconv"
        "strings"
    )
    
    type Process struct {
        pid int
        cpu float64
    }
    
    func main() {
        cmd := exec.Command("ps", "aux")
        var out bytes.Buffer
        cmd.Stdout = &out
        err := cmd.Run()
        if err != nil {
            log.Fatal(err)
        }
        processes := make([]*Process, 0)
        for {
            line, err := out.ReadString('\n')
            if err!=nil {
                break;
            }
            tokens := strings.Split(line, " ")
            ft := make([]string, 0)
            for _, t := range(tokens) {
                if t!="" && t!="\t" {
                    ft = append(ft, t)
                }
            }
            log.Println(len(ft), ft)
            pid, err := strconv.Atoi(ft[1])
            if err!=nil {
                continue
            }
            cpu, err := strconv.ParseFloat(ft[2], 64)
            if err!=nil {
                log.Fatal(err)
            }
            processes = append(processes, &Process{pid, cpu})
        }
        for _, p := range(processes) {
            log.Println("Process ", p.pid, " takes ", p.cpu, " % of the CPU")
        }
    }
    

提交回复
热议问题