提交 13e0d343 编写于 作者: K KenjiTakahashi

CPUPercent

上级 ab23ece7
......@@ -3,6 +3,7 @@ package gopsutil
import (
"encoding/json"
"runtime"
"time"
)
type CPUTimesStat struct {
......@@ -39,6 +40,57 @@ func CPUCounts(logical bool) (int, error) {
return runtime.NumCPU(), nil
}
var lastCPUTimes []CPUTimesStat
var lastPerCPUTimes []CPUTimesStat
func CPUPercent(interval time.Duration, percpu bool) ([]float32, error) {
getAllBusy := func(t CPUTimesStat) (float32, float32) {
busy := t.User + t.System + t.Nice + t.Iowait + t.Irq +
t.Softirq + t.Steal + t.Guest + t.GuestNice + t.Stolen
return busy + t.Idle, busy
}
calculate := func(t1, t2 CPUTimesStat) float32 {
t1All, t1Busy := getAllBusy(t1)
t2All, t2Busy := getAllBusy(t2)
if t2Busy <= t1Busy {
return 0
}
return (t2Busy - t1Busy) / (t2All - t1All) * 100
}
cpuTimes, err := CPUTimes(percpu)
if err != nil {
return nil, err
}
if interval > 0 {
if !percpu {
lastCPUTimes = cpuTimes
} else {
lastPerCPUTimes = cpuTimes
}
time.Sleep(interval)
cpuTimes, err = CPUTimes(percpu)
if err != nil {
return nil, err
}
}
ret := make([]float32, len(cpuTimes))
if !percpu {
ret[0] = calculate(lastCPUTimes[0], cpuTimes[0])
lastCPUTimes = cpuTimes
} else {
for i, t := range cpuTimes {
ret[i] = calculate(lastPerCPUTimes[i], t)
}
lastPerCPUTimes = cpuTimes
}
return ret, nil
}
func (c CPUTimesStat) String() string {
s, _ := json.Marshal(c)
return string(s)
......@@ -48,3 +100,8 @@ func (c CPUInfoStat) String() string {
s, _ := json.Marshal(c)
return string(s)
}
func init() {
lastCPUTimes, _ = CPUTimes(false)
lastPerCPUTimes, _ = CPUTimes(true)
}
......@@ -2,7 +2,9 @@ package gopsutil
import (
"fmt"
"runtime"
"testing"
"time"
)
func TestCpu_times(t *testing.T) {
......@@ -55,3 +57,33 @@ func TestCpuInfo(t *testing.T) {
}
}
}
func testCPUPercent(t *testing.T, percpu bool) {
v, err := CPUPercent(time.Millisecond, percpu)
if err != nil {
t.Errorf("error %v", err)
}
numcpu := runtime.NumCPU()
if (percpu && len(v) != numcpu) || (!percpu && len(v) != 1) {
t.Fatalf("wrong number of entries from CPUPercent: %v", v)
}
for i := 0; i < 1000; i++ {
v, err := CPUPercent(0, percpu)
if err != nil {
t.Errorf("error %v", err)
}
for _, percent := range v {
if percent < 0.0 || percent > 100.0*float32(numcpu) {
t.Fatalf("CPUPercent value is invalid: %f", percent)
}
}
}
}
func TestCPUPercent(t *testing.T) {
testCPUPercent(t, false)
}
func TestCPUPercentPerCpu(t *testing.T) {
testCPUPercent(t, true)
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册