Skip to content

Commit

Permalink
fix getProcessCpuStat return value (in percentage) breaks compatibility.
Browse files Browse the repository at this point in the history
  • Loading branch information
sunyucheng committed Jul 2, 2023
1 parent 0807185 commit 0e75426
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
5 changes: 5 additions & 0 deletions core/system_metric/sys_metric_stat.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package system_metric

import (
"os"
"runtime"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -176,6 +177,10 @@ func retrieveAndUpdateCpuStat() {
return
}

// fix getProcessCpuStat return value (in percentage) breaks compatibility.
cpuNum := runtime.NumCPU()
cpuPercent = cpuPercent / float64(cpuNum) / 100.0

cpuRatioGauge.Set(cpuPercent)

currentCpuUsage.Store(cpuPercent)
Expand Down
42 changes: 27 additions & 15 deletions core/system_metric/sys_metric_stat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,8 @@ func TestCurrentCpuUsage(t *testing.T) {
assert.True(t, util.Float64Equals(v, cpuUsage))
}

func Test_getProcessCpuStat(t *testing.T) {
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
i := 0
wg.Done()
for i < 10000000000 {
i++
if i == 1000000000 {
i = 0
}
}
}()
wg.Wait()

func TestGetProcessCpuStat(t *testing.T) {
upraiseCpuRate()
got, err := getProcessCpuStat()
if err != nil {
t.Error(err)
Expand All @@ -83,3 +70,28 @@ func Test_getProcessCpuStat(t *testing.T) {
assert.True(t, int(got) > 0)
time.Sleep(time.Millisecond * 200)
}

func TestRetrieveAndUpdateCpuStatReturnValueRange(t *testing.T) {
// Initial cpu retrieval.
retrieveAndUpdateCpuStat()
upraiseCpuRate()
time.Sleep(time.Millisecond * 200)
retrieveAndUpdateCpuStat()
assert.True(t, true, CurrentCpuUsage() < 1.0)
}

func upraiseCpuRate() {
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
i := 0
wg.Done()
for i < 10000000000 {
i++
if i == 1000000000 {
i = 0
}
}
}()
wg.Wait()
}

0 comments on commit 0e75426

Please sign in to comment.