summaryrefslogtreecommitdiffstats
path: root/widgets/cpu.go
blob: 11edd901390c0e71044c969db05640bc768c9738 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package widgets

import (
	"strconv"
	"time"

	ui "github.com/cjbassi/gotop/termui"
	ps "github.com/shirou/gopsutil/cpu"
)

type CPU struct {
	*ui.LineGraph
	count    int
	interval time.Duration
}

func NewCPU() *CPU {
	count, _ := ps.Counts(false)
	c := &CPU{ui.NewLineGraph(), count, time.Second}
	c.Label = "CPU Usage"
	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() {
	percent, _ := ps.Percent(time.Second, true) // takes one second to get the data
	for i := 0; i < c.count; i++ {
		key := "CPU" + strconv.Itoa(i+1)
		c.Data[key] = append(c.Data[key], percent[i])
	}
}