go: 打印ubuntu下的进程cpu 内存占用

2020-01-20 11:16:04 浏览数 (1)

直接使用gopsutil这个包,非常的方便

代码语言:javascript复制
package main

import (
    "github.com/dalianzhu/logger"
    "github.com/shirou/gopsutil/process"
    "sort"
    "time"
)

type processNameCpu struct {
    Name string
    Cpu  float64
    Mem  float32
}

func main() {
    logger.InitLogging(logger.FILE, "cpus.log", "/home/log", 2, logger.INFO)
    for {
        syspros, _ := process.Processes()
        pros := make([]*processNameCpu, 0, 100)
        for _, pro := range syspros {
            name, _ := pro.Name()
            percent, _ := pro.CPUPercent()
            mem, _ := pro.MemoryPercent()
            pros = append(pros, &processNameCpu{name, percent, mem})
        }
        // 按cpu排序,取前20名打印
        sort.Slice(pros, func(i, j int) bool {
            return pros[i].Cpu > pros[j].Cpu
        })

        for _, pro := range pros[:20] {
            logger.Infof("%v %v %v", pro.Name, pro.Cpu, pro.Mem)
        }
        logger.Infoln("**********************")
        time.Sleep(time.Second * 2)
    }
}

0 人点赞