|
@@ -1,39 +1,23 @@
|
|
|
package main
|
|
|
|
|
|
import (
|
|
|
- "bufio"
|
|
|
+ "bytes"
|
|
|
"flag"
|
|
|
"fmt"
|
|
|
"github.com/oz123/gupta"
|
|
|
- "log"
|
|
|
"os"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
-func readFirstLine(rd *bufio.Reader, f *os.File) string {
|
|
|
- line, err := rd.ReadString('\n')
|
|
|
- if err != nil {
|
|
|
- log.Fatalf("could not read /proc/stat, error: %v", err)
|
|
|
- }
|
|
|
- rd.Reset(f)
|
|
|
- f.Seek(0, 0)
|
|
|
+func readProcStatLine(r *os.File) string {
|
|
|
+ buf := make([]byte, 80)
|
|
|
+ r.ReadAt(buf, 0)
|
|
|
+ idx := bytes.Index(buf, []byte("cpu0"))
|
|
|
+ line := string(buf[:idx])
|
|
|
+ r.Seek(0, 0)
|
|
|
return line
|
|
|
}
|
|
|
|
|
|
-func readProcStatLines(freq int) (string, string) {
|
|
|
- var line, newline string
|
|
|
- f, err := os.Open("/proc/stat")
|
|
|
- if err != nil {
|
|
|
- log.Fatalf("could not read /proc/stat, error: %v", err)
|
|
|
- }
|
|
|
- defer f.Close()
|
|
|
- rd := bufio.NewReader(f)
|
|
|
- line = readFirstLine(rd, f)
|
|
|
- time.Sleep(time.Duration(freq) * time.Second)
|
|
|
- newline = readFirstLine(rd, f)
|
|
|
- return line, newline
|
|
|
-}
|
|
|
-
|
|
|
func main() {
|
|
|
var freq int
|
|
|
var partition, netInterface string
|
|
@@ -50,9 +34,12 @@ func main() {
|
|
|
flag.Parse()
|
|
|
|
|
|
fmt.Println(gupta.Hello())
|
|
|
+ r, _ := os.Open("/proc/stat")
|
|
|
|
|
|
for true {
|
|
|
- line, lineNew := readProcStatLines(freq)
|
|
|
+ line := readProcStatLine(r)
|
|
|
+ time.Sleep(time.Second)
|
|
|
+ lineNew := readProcStatLine(r)
|
|
|
cpustat := gupta.NewCPUStat(line, lineNew)
|
|
|
fmt.Printf("CPU usage %.2f%%\n", cpustat.CPUUsage())
|
|
|
}
|