xmtop/src/widgets/cpu.go

70 lines
1.4 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
"time"
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
2018-04-12 02:53:38 +08:00
Count int // number of cores
2018-08-01 05:24:44 +08:00
Average bool // show average load
PerCPU bool // show per-core load
2018-02-19 15:25:02 +08:00
interval time.Duration
}
2018-08-01 05:24:44 +08:00
func NewCPU(interval time.Duration, zoom int, average bool, percpu bool) *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-08-01 05:24:44 +08:00
Average: average,
PerCPU: percpu,
2018-03-04 09:05:52 +08:00
}
2018-03-28 05:27:23 +08:00
self.Label = "CPU Usage"
self.Zoom = zoom
2018-08-01 05:24:44 +08:00
if self.Average {
2018-03-28 05:27:23 +08:00
self.Data["Average"] = []float64{0}
2018-02-19 15:25:02 +08:00
}
2018-08-01 05:24:44 +08:00
if self.PerCPU {
for i := 0; i < self.Count; i++ {
k := fmt.Sprintf("CPU%d", i)
self.Data[k] = []float64{0}
}
}
2018-04-13 11:00:34 +08:00
2018-03-28 05:27:23 +08:00
ticker := time.NewTicker(self.interval)
2018-02-19 15:25:02 +08:00
go func() {
2018-08-01 05:24:44 +08:00
self.update()
2018-02-19 15:25:02 +08:00
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-08-01 05:24:44 +08:00
if self.Average {
2018-03-28 05:27:23 +08:00
percent, _ := psCPU.Percent(self.interval, false)
self.Data["Average"] = append(self.Data["Average"], percent[0])
self.Labels["Average"] = fmt.Sprintf("%3.0f%%", percent[0])
2018-02-19 15:25:02 +08:00
}
2018-08-01 05:24:44 +08:00
if self.PerCPU {
percents, _ := psCPU.Percent(self.interval, true)
for i := 0; i < self.Count; i++ {
k := fmt.Sprintf("CPU%d", i)
self.Data[k] = append(self.Data[k], percents[i])
self.Labels[k] = fmt.Sprintf("%3.0f%%", percents[i])
}
}
2018-02-19 15:25:02 +08:00
}