| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 | 
							- package gupta
 
- import (
 
- 	"fmt"
 
- 	"strconv"
 
- 	"strings"
 
- )
 
- // collect all CPU stat from /proc/cpustat
 
- type CPUStat struct {
 
- 	totalTime    float64
 
- 	idleTime     float64
 
- 	totalTimeNew float64
 
- 	idleTimeNew  float64
 
- }
 
- func (c *CPUStat) ReadInfoNew(statline string) {
 
- 	rawInfo := strings.Fields(statline)
 
- 	idleNew, _ := strconv.ParseFloat(rawInfo[4], 10)
 
- 	iowaitNew, _ := strconv.ParseFloat(rawInfo[5], 10)
 
- 	c.idleTimeNew = idleNew + iowaitNew
 
- 	for _, s := range rawInfo {
 
- 		u, _ := strconv.ParseFloat(s, 10)
 
- 		c.totalTimeNew += u
 
- 	}
 
- }
 
- func (c *CPUStat) ReadInfo(statline string) {
 
- 	rawInfo := strings.Fields(statline)
 
- 	for _, s := range rawInfo[1:] {
 
- 		u, _ := strconv.ParseFloat(s, 10)
 
- 		c.totalTime += u
 
- 	}
 
- 	idle, _ := strconv.ParseFloat(rawInfo[4], 10)
 
- 	iowait, _ := strconv.ParseFloat(rawInfo[5], 10)
 
- 	c.idleTime = idle + iowait
 
- }
 
- func (c *CPUStat) CPUUsage() float64 {
 
- 	deltaIdleTime := c.idleTimeNew - c.idleTime
 
- 	deltaTotalTime := c.totalTimeNew - c.totalTime
 
- 	cpuUsage := (1.0 - float64(deltaIdleTime)/float64(deltaTotalTime)) * 100
 
- 	return cpuUsage
 
- }
 
- func NewCPUStat(procstatline, procstatlineNew string) CPUStat {
 
- 	cpustat := CPUStat{}
 
- 	cpustat.ReadInfo(procstatline)
 
- 	cpustat.ReadInfoNew(procstatlineNew)
 
- 	return cpustat
 
- }
 
- func (c CPUStat) MarshalJSON() ([]byte, error) {
 
- 	jsonData := []byte(
 
- 		fmt.Sprintf("{\"cpu usage\": \"%.2f%%\"}", c.CPUUsage()))
 
- 	return jsonData, nil
 
- }
 
 
  |