Skip to content

Commit 0e75426

Browse files
committed
fix getProcessCpuStat return value (in percentage) breaks compatibility.
1 parent 0807185 commit 0e75426

File tree

2 files changed

+32
-15
lines changed

2 files changed

+32
-15
lines changed

core/system_metric/sys_metric_stat.go

+5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package system_metric
1616

1717
import (
1818
"os"
19+
"runtime"
1920
"sync"
2021
"sync/atomic"
2122
"time"
@@ -176,6 +177,10 @@ func retrieveAndUpdateCpuStat() {
176177
return
177178
}
178179

180+
// fix getProcessCpuStat return value (in percentage) breaks compatibility.
181+
cpuNum := runtime.NumCPU()
182+
cpuPercent = cpuPercent / float64(cpuNum) / 100.0
183+
179184
cpuRatioGauge.Set(cpuPercent)
180185

181186
currentCpuUsage.Store(cpuPercent)

core/system_metric/sys_metric_stat_test.go

+27-15
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,8 @@ func TestCurrentCpuUsage(t *testing.T) {
4747
assert.True(t, util.Float64Equals(v, cpuUsage))
4848
}
4949

50-
func Test_getProcessCpuStat(t *testing.T) {
51-
wg := &sync.WaitGroup{}
52-
wg.Add(1)
53-
go func() {
54-
i := 0
55-
wg.Done()
56-
for i < 10000000000 {
57-
i++
58-
if i == 1000000000 {
59-
i = 0
60-
}
61-
}
62-
}()
63-
wg.Wait()
64-
50+
func TestGetProcessCpuStat(t *testing.T) {
51+
upraiseCpuRate()
6552
got, err := getProcessCpuStat()
6653
if err != nil {
6754
t.Error(err)
@@ -83,3 +70,28 @@ func Test_getProcessCpuStat(t *testing.T) {
8370
assert.True(t, int(got) > 0)
8471
time.Sleep(time.Millisecond * 200)
8572
}
73+
74+
func TestRetrieveAndUpdateCpuStatReturnValueRange(t *testing.T) {
75+
// Initial cpu retrieval.
76+
retrieveAndUpdateCpuStat()
77+
upraiseCpuRate()
78+
time.Sleep(time.Millisecond * 200)
79+
retrieveAndUpdateCpuStat()
80+
assert.True(t, true, CurrentCpuUsage() < 1.0)
81+
}
82+
83+
func upraiseCpuRate() {
84+
wg := &sync.WaitGroup{}
85+
wg.Add(1)
86+
go func() {
87+
i := 0
88+
wg.Done()
89+
for i < 10000000000 {
90+
i++
91+
if i == 1000000000 {
92+
i = 0
93+
}
94+
}
95+
}()
96+
wg.Wait()
97+
}

0 commit comments

Comments
 (0)