xmtop/widgets/cpu.go

74 lines
1.6 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
import (
2018-04-11 11:08:02 +08:00
"fmt"
2018-02-19 15:25:02 +08:00
"strconv"
"time"
2018-04-11 11:08:02 +08:00
"github.com/cjbassi/gotop/utils"
2018-03-30 06:48:43 +08:00
ui "github.com/cjbassi/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++ {
2018-04-10 00:55:10 +08:00
key := "CPU" + strconv.Itoa(i)
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-04-11 12:03:13 +08:00
// calculates the CPU usage over a 1 second interval and blocks for the duration
2018-03-28 05:27:23 +08:00
func (self *CPU) update() {
2018-04-11 12:03:13 +08:00
// show average cpu usage if more than 8 cores
2018-03-28 05:27:23 +08:00
if self.Count <= 8 {
2018-04-10 01:46:11 +08:00
percents, _ := psCPU.Percent(self.interval, true)
if len(percents) != self.Count {
2018-04-10 04:04:58 +08:00
count, _ := psCPU.Counts(false)
2018-04-11 11:08:02 +08:00
utils.Error("CPU percentages",
fmt.Sprint(
"self.Count: ", self.Count, "\n",
"gopsutil.Counts(): ", count, "\n",
"len(percents): ", len(percents), "\n",
"percents: ", percents, "\n",
"self.interval: ", self.interval,
))
2018-04-10 01:46:11 +08:00
}
2018-03-28 05:27:23 +08:00
for i := 0; i < self.Count; i++ {
2018-04-10 00:55:10 +08:00
key := "CPU" + strconv.Itoa(i)
2018-04-10 01:46:11 +08:00
percent := percents[i]
self.Data[key] = append(self.Data[key], percent)
}
} 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
}
}