xmtop/widgets/cpu.go

59 lines
1.2 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
import (
"strconv"
"time"
ui "github.com/cjbassi/gotop/termui"
2018-03-04 09:05:52 +08:00
psCPU "github.com/shirou/gopsutil/cpu"
2018-02-19 15:25:02 +08:00
)
type CPU struct {
*ui.LineGraph
Count int // number of CPUs
2018-02-19 15:25:02 +08:00
interval time.Duration
}
2018-03-10 08:29:05 +08:00
func NewCPU(interval time.Duration, zoom int) *CPU {
2018-03-04 09:05:52 +08:00
count, _ := psCPU.Counts(false)
2018-03-28 05:27:23 +08:00
self := &CPU{
2018-03-04 09:05:52 +08:00
LineGraph: ui.NewLineGraph(),
Count: count,
2018-03-09 16:27:46 +08:00
interval: interval,
2018-03-04 09:05:52 +08:00
}
2018-03-28 05:27:23 +08:00
self.Label = "CPU Usage"
self.Zoom = zoom
if self.Count <= 8 {
for i := 0; i < self.Count; i++ {
key := "CPU" + strconv.Itoa(i+1)
2018-03-28 05:27:23 +08:00
self.Data[key] = []float64{0}
}
} else {
2018-03-28 05:27:23 +08:00
self.Data["Average"] = []float64{0}
2018-02-19 15:25:02 +08:00
}
2018-03-28 05:27:23 +08:00
go self.update()
ticker := time.NewTicker(self.interval)
2018-02-19 15:25:02 +08:00
go func() {
for range ticker.C {
2018-03-28 05:27:23 +08:00
self.update()
2018-02-19 15:25:02 +08:00
}
}()
2018-03-28 05:27:23 +08:00
return self
2018-02-19 15:25:02 +08:00
}
2018-03-28 05:27:23 +08:00
func (self *CPU) update() {
2018-02-23 16:42:39 +08:00
// psutil calculates the CPU usage over a 1 second interval, therefore it blocks for 1 second
2018-03-28 05:27:23 +08:00
if self.Count <= 8 {
percent, _ := psCPU.Percent(self.interval, true)
for i := 0; i < self.Count; i++ {
key := "CPU" + strconv.Itoa(i+1)
2018-03-28 05:27:23 +08:00
self.Data[key] = append(self.Data[key], percent[i])
}
} else {
2018-03-28 05:27:23 +08:00
percent, _ := psCPU.Percent(self.interval, false)
self.Data["Average"] = append(self.Data["Average"], percent[0])
2018-02-19 15:25:02 +08:00
}
}