Browse Source

Add a method to calculate CPU Usage

Oz Tiram 5 years ago
parent
commit
9f99cf1c4d
2 changed files with 18 additions and 8 deletions
  1. 4 0
      gupta.go
  2. 14 8
      gupta_test.go

+ 4 - 0
gupta.go

@@ -85,6 +85,10 @@ func (c *CPUStat) IdleTime() uint64 {
 	return c.idle + c.iowait
 }
 
+func (c *CPUStat) CPUUsage() uint64 {
+	return c.TotalTime() - c.IdleTime()
+}
+
 func NewCPUStat(procstatline string) CPUStat {
 	cpustat := CPUStat{}
 	statline := strings.Fields(procstatline)

+ 14 - 8
gupta_test.go

@@ -33,8 +33,13 @@ func TestRunGupta(t *testing.T) {
 }
 
 func TestCPUStat(t *testing.T) {
+	//               0    1    2     3     4     5      6     7       8     9     10
+	//               cpu user nice system idle iowait  irq  softirq steal guest guest_nice
+	procstatLine := "cpu 4705 356  584    3699   23    23     0       0     0    0"
+	cpustat := NewCPUStat(procstatLine)
 
 	t.Run("Test that gupta hast Report", func(t *testing.T) {
+
 		// test we can get some report struct from gupta
 		report := GuptaReport{
 			cpuLoad:     0.2,
@@ -53,6 +58,7 @@ func TestCPUStat(t *testing.T) {
 	})
 
 	t.Run("Test the CPUStat can read info", func(t *testing.T) {
+
 		cpustat := CPUStat{}
 		cpustat.ReadInfo([]string{
 			"4705",
@@ -72,10 +78,6 @@ func TestCPUStat(t *testing.T) {
 	})
 
 	t.Run("Test the NewCPUStat can create an instance", func(t *testing.T) {
-		//               0    1    2     3     4     5      6     7       8     9     10
-		//               cpu user nice system idle iowait  irq  softirq steal guest guest_nice
-		procstatLine := "cpu 4705 356  584    3699   23    23     0       0     0    0"
-		cpustat := NewCPUStat(procstatLine)
 
 		got := cpustat.user
 		want := uint64(4705)
@@ -84,8 +86,6 @@ func TestCPUStat(t *testing.T) {
 	})
 
 	t.Run("Test that Total CPUTime calculates properly", func(t *testing.T) {
-		procstatLine := "cpu 4705 356  584    3699   23    23     0       0     0    0"
-		cpustat := NewCPUStat(procstatLine)
 
 		got := cpustat.TotalTime()
 		want := cpustat.user + cpustat.nice + cpustat.system + cpustat.idle + cpustat.iowait +
@@ -95,8 +95,6 @@ func TestCPUStat(t *testing.T) {
 	})
 
 	t.Run("Test that IdleTime calculates properly", func(t *testing.T) {
-		procstatLine := "cpu 4705 356  584    3699   23    23     0       0     0    0"
-		cpustat := NewCPUStat(procstatLine)
 
 		got := cpustat.IdleTime()
 		want := uint64(3722)
@@ -104,6 +102,14 @@ func TestCPUStat(t *testing.T) {
 		assert(t, name, got, want)
 
 	})
+
+	t.Run("Test that CPUUsage calculates properly", func(t *testing.T) {
+
+		got := cpustat.CPUUsage()
+		want := uint64(5668)
+		assert(t, "CPUUsage", got, want)
+
+	})
 }
 
 func assert(t *testing.T, name string, got, want uint64) {