go-utils/stats/cpu.go

40 lines
539 B
Go
Raw Normal View History

2021-08-14 21:19:37 +00:00
package stats
import (
"fmt"
"math"
"os"
"runtime"
"github.com/struCoder/pidusage"
)
type StatCPU struct {
// Percent of CPU Usage
Usage string
// Number of CPUs
Num int
// CPU Arch
Arch string
}
// Get CPU stats
func CPU() (StatCPU, error) {
2021-08-14 21:19:37 +00:00
pid := os.Getpid()
stat := StatCPU{
Num: runtime.NumCPU(),
Arch: runtime.GOARCH,
}
sysInfo, err := pidusage.GetStat(pid)
if err != nil {
stat.Usage = "error"
return stat, err
}
stat.Usage = fmt.Sprint(math.Round(sysInfo.CPU*100)/100, "%")
return stat, nil
2021-08-14 21:19:37 +00:00
}