首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Golang中获得内存度量、磁盘度量和CPU度量?

如何在Golang中获得内存度量、磁盘度量和CPU度量?
EN

Stack Overflow用户
提问于 2022-08-22 18:13:49
回答 1查看 389关注 0票数 0

我是新来的,我试图得到3个函数来返回它们,如下所示

  1. 函数1-返回系统的内存使用情况
  2. 函数2-返回系统的磁盘使用情况
  3. 函数3-返回系统的CPU使用情况

到目前为止,我只能做到这一点(PS:尽量不使用任何语言)

代码语言:javascript
复制
func getCPUTrack() (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
}

idle0, total0 := getCPUTrack()
    time.Sleep(3 * time.Second)
    idle1, total1 := getCPUTrack()

    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)

有人能帮我吗?谢谢

EN

回答 1

Stack Overflow用户

发布于 2022-08-23 14:18:39

有一个非常酷的库,您可以使用上钩,或者详细查看它是如何实现的,这样您就可以构建自己的库了。

我开发了一个客户机,它使用这个库并在后台运行,发送内存和CPU使用情况

代码语言:javascript
复制
package main

import (
    "fmt"
    "os"
    "time"

    "github.com/mackerelio/go-osstat/cpu"
    "github.com/mackerelio/go-osstat/memory"
)

const (
    memoryMetric = "memory"
    cpuMetric    = "cpu"
    retries      = 10
)

type client struct {
    packageName     string
    memoryIteration int
    cpuIteration    int
    OSClient        OSClient
}

type Client interface {
    EmitMetrics()
}

type osClient struct{}

type OSClient interface {
    GetMemory() (*memory.Stats, error)
    GetCPU() (*cpu.Stats, error)
}

func (osc osClient) GetMemory() (*memory.Stats, error) { return memory.Get() }

func (osc osClient) GetCPU() (*cpu.Stats, error) { return cpu.Get() }

func NewClient(packageName string, memoryIteration, cpuIteration int) Client {
    return newClient(packageName, memoryIteration, cpuIteration, osClient{})
}

func newClient(packageName string, memoryIteration, cpuIteration int, osclient OSClient) Client {
    return &client{
        packageName:     packageName,
        memoryIteration: memoryIteration,
        cpuIteration:    cpuIteration,
        OSClient:        osclient,
    }
}

func (c *client) EmitMetrics() {
    protectFromPanic := func(metric string) {
        if r := recover(); r != nil {
            fmt.Printf(fmt.Sprintf("Recover from fail sending %s metrics for %s", metric, c.packageName), zap.Any("recover", r))
        }
    }
    c.sendMemoryMetrics(protectFromPanic)
    c.sendCPUMetrics(protectFromPanic)
}

func (c *client) sendMemoryMetrics(f func(string)) {
    count := 0
    go func() {
        defer func() {
            f(memoryMetric)
        }()
        for {
            memory, err := c.OSClient.GetMemory()
            if err != nil {
                fmt.Fprintf(os.Stderr, "%s\n", err)
                count++
                if count == retries {
                    return
                }
            } else {
                count = 0
                EmitMemoryMetrics(c.packageName, memory.Total, memory.Used, memory.Cached, memory.Free)
                time.Sleep(time.Duration(c.memoryIteration) * time.Millisecond)
            }
        }
    }()
}

func (c *client) sendCPUMetrics(f func(string)) {
    go func() {
        defer func() {
            f(cpuMetric)
        }()
        for {
            before, err := c.OSClient.GetCPU()
            if err != nil {
                fmt.Fprintf(os.Stderr, "%s\n", err)

                return
            }
            time.Sleep(time.Duration(c.cpuIteration) * time.Millisecond)
            after, err := c.OSClient.GetCPU()
            if err != nil {
                fmt.Fprintf(os.Stderr, "%s\n", err)

                return
            }
            total := float64(after.Total - before.Total)
            EmitCPUMetrics(c.packageName,
                total,
                float64(after.User-before.User)/total*100,
                float64(after.System-before.System)/total*100,
                float64(after.Idle-before.Idle)/total*100)
        }
    }()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73449394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档