Last active
January 12, 2019 15:10
-
-
Save jbdrvl/991830573ddd0c45557b71251d006407 to your computer and use it in GitHub Desktop.
Prints CPU(s) usage and updates it in real time by accessing the CPU info in /proc/stat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"log" | |
"bufio" | |
"strconv" | |
"strings" | |
"runtime" | |
"time" | |
tm "github.com/buger/goterm" // `go get github.com/buger/goterm` | |
) | |
type cpu_val struct { | |
idle int | |
total int | |
} | |
func main() { | |
tm.Clear() | |
num_CPU := runtime.NumCPU() | |
tm.MoveCursor(1,1) | |
tm.Println("Nbr of CPU(s):", num_CPU) | |
file, err := os.Open("/proc/stat") | |
check(err) | |
reader := bufio.NewReader(file) | |
reader.ReadString('\n') | |
var cpu_infos_prev = make([]cpu_val, num_CPU) | |
for i:=0; i<num_CPU; i++ { | |
cpu_line, err := reader.ReadString('\n') | |
check(err) | |
idle, total := getValues(cpu_line) | |
var new_cpu_val = cpu_val {idle, total} | |
cpu_infos_prev = append(cpu_infos_prev, new_cpu_val) | |
} | |
for { | |
time.Sleep(1 * time.Second) | |
file, err = os.Open("/proc/stat") | |
check(err) | |
reader = bufio.NewReader(file) | |
reader.ReadString('\n') | |
for i:=0; i<num_CPU; i++ { | |
cpu_line, err := reader.ReadString('\n') | |
check(err) | |
idle, total := getValues(cpu_line) | |
diff_total := total - cpu_infos_prev[i].total + 1 // to avoid div by 0 | |
diff_idle := idle - cpu_infos_prev[i].idle | |
percentage := 100*(float64(diff_total - diff_idle)/float64(diff_total)) | |
cpu_infos_prev[i].total = total | |
cpu_infos_prev[i].idle = idle | |
tm.MoveCursor(1, i+2) | |
tm.Printf("CPU %d: %.1f%% ", i+1, percentage) | |
} | |
tm.Printf("\n") | |
tm.Flush() | |
} | |
} | |
func check(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func getValues(cpu string) (int, int) { | |
values := strings.Split(cpu, " ") | |
total := 0 | |
idle := 0 | |
for i:=1; i<len(values); i++ { | |
new_val, err := strconv.Atoi(strings.Replace(values[i], "\n", "", 1)) | |
check(err) | |
total += new_val | |
if i==4 { | |
idle = new_val | |
} | |
} | |
return idle, total | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment