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
|
2018-02-23 16:42:39 +08:00
|
|
|
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)
|
|
|
|
c := &CPU{
|
|
|
|
LineGraph: ui.NewLineGraph(),
|
|
|
|
count: count,
|
2018-03-09 16:27:46 +08:00
|
|
|
interval: interval,
|
2018-03-04 09:05:52 +08:00
|
|
|
}
|
2018-02-19 15:25:02 +08:00
|
|
|
c.Label = "CPU Usage"
|
2018-03-10 08:29:05 +08:00
|
|
|
c.Zoom = zoom
|
2018-02-19 15:25:02 +08:00
|
|
|
for i := 0; i < c.count; i++ {
|
|
|
|
key := "CPU" + strconv.Itoa(i+1)
|
|
|
|
c.Data[key] = []float64{0}
|
|
|
|
}
|
|
|
|
|
|
|
|
go c.update()
|
|
|
|
ticker := time.NewTicker(c.interval)
|
|
|
|
go func() {
|
|
|
|
for range ticker.C {
|
|
|
|
c.update()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *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
|
|
|
|
// `true` makes it so psutil doesn't group CPU usage percentages
|
2018-03-09 16:27:46 +08:00
|
|
|
percent, _ := psCPU.Percent(c.interval, true)
|
2018-02-19 15:25:02 +08:00
|
|
|
for i := 0; i < c.count; i++ {
|
|
|
|
key := "CPU" + strconv.Itoa(i+1)
|
|
|
|
c.Data[key] = append(c.Data[key], percent[i])
|
|
|
|
}
|
|
|
|
}
|