Browse Source

Add function to calculate total cpu time

Oz Tiram 5 years ago
parent
commit
2c7ccf4aa8
2 changed files with 23 additions and 8 deletions
  1. 4 0
      gupta.go
  2. 19 8
      gupta_test.go

+ 4 - 0
gupta.go

@@ -77,6 +77,10 @@ func (c *CPUStat) ReadInfo(rawInfo []string) {
 	}
 }
 
+func (c *CPUStat) TotalTime() uint64 {
+	return c.User + c.nice + c.system + c.idle + c.iowait + c.irq + c.softirq + c.steal
+}
+
 func NewCPUStat(procstatline string) CPUStat {
 	cpustat := CPUStat{}
 	statline := strings.Fields(procstatline)

+ 19 - 8
gupta_test.go

@@ -48,10 +48,9 @@ func TestGuptaHasReport(t *testing.T) {
 
 }
 
-func TestGetCPULoad(t *testing.T) {
+func TestGetCPUUsage(t *testing.T) {
 	cpustat := CPUStat{}
 	cpustat.ReadInfo([]string{
-		"cpu",
 		"4705",
 		"356",
 		"584",
@@ -62,19 +61,31 @@ func TestGetCPULoad(t *testing.T) {
 		"0",
 		"0",
 		"0"})
-
-	if cpustat.user != 4705 {
-		t.Errorf("got %v want %v", cpustat.user, 4705)
+	if cpustat.User != 4705 {
+		t.Errorf("Got cpustat.User %v want %v", cpustat.User, 4705)
 	}
 }
 
-func TestCalculateCPUUsage(t *testing.T) {
+func TestNewCPUUsage(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)
 
-	if cpustat.user != 4705 {
-		t.Errorf("got %v want %v", cpustat.user, 4705)
+	if cpustat.User != 4705 {
+		t.Errorf("got %v want %v", cpustat.User, 4705)
+	}
+}
+
+func TestTotalCPUTime(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 +
+		cpustat.irq + cpustat.softirq + cpustat.steal
+
+	if got != want {
+		t.Errorf("got total time %v want %v", got, want)
 	}
 }