You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/pkg/stat/sys/cpu/cpu.go

69 lines
1.0 KiB

6 years ago
package cpu
import (
"fmt"
"sync/atomic"
"time"
)
const (
interval time.Duration = time.Millisecond * 500
)
6 years ago
var (
stats CPU
usage uint64
6 years ago
)
6 years ago
// CPU is cpu stat usage.
type CPU interface {
Usage() (u uint64, e error)
Info() Info
}
6 years ago
func init() {
var (
err error
)
stats, err = newCgroupCPU()
6 years ago
if err != nil {
6 years ago
// fmt.Printf("cgroup cpu init failed(%v),switch to psutil cpu\n", err)
stats, err = newPsutilCPU(interval)
if err != nil {
panic(fmt.Sprintf("cgroup cpu init failed!err:=%v", err))
6 years ago
}
}
go func() {
ticker := time.NewTicker(interval)
6 years ago
defer ticker.Stop()
for {
<-ticker.C
u, err := stats.Usage()
if err == nil && u != 0 {
atomic.StoreUint64(&usage, u)
6 years ago
}
}
}()
}
// Stat cpu stat.
type Stat struct {
Usage uint64 // cpu use ratio.
}
// Info cpu info.
type Info struct {
Frequency uint64
Quota float64
}
// ReadStat read cpu stat.
func ReadStat(stat *Stat) {
stat.Usage = atomic.LoadUint64(&usage)
}
// GetInfo get cpu info.
func GetInfo() Info {
return stats.Info()
6 years ago
}