use goroutine to record cpu usage

This commit is contained in:
0xJacky 2022-02-22 00:17:59 +08:00
parent 16a3d02d9c
commit 897c3cddcd
7 changed files with 134 additions and 63 deletions

View file

@ -3,6 +3,7 @@ package api
import (
"encoding/json"
"fmt"
"github.com/0xJacky/Nginx-UI/server/tool"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/host"
@ -97,3 +98,10 @@ func Analytic(c *gin.Context) {
}
}
}
func GetCpuUsageRecord(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"user": tool.CpuUserBuffer,
"total": tool.CpuTotalBuffer,
})
}

View file

@ -38,6 +38,7 @@ func InitRouter() *gin.Engine {
g := g.Group("/", authRequired())
{
g.GET("/analytic", api.Analytic)
g.GET("/analytic/cpu", api.GetCpuUsageRecord)
g.GET("/users", api.GetUsers)
g.GET("/user/:id", api.GetUser)

45
server/tool/cpu_usage.go Normal file
View file

@ -0,0 +1,45 @@
package tool
import (
"github.com/shirou/gopsutil/v3/cpu"
"runtime"
"time"
)
type cpuUsage struct {
Time time.Time `json:"x"`
Usage float64 `json:"y"`
}
var CpuUserBuffer []cpuUsage
var CpuTotalBuffer []cpuUsage
func RecordCpuUsage() {
for {
cpuTimesBefore, _ := cpu.Times(false)
time.Sleep(1000 * time.Millisecond)
cpuTimesAfter, _ := cpu.Times(false)
threadNum := runtime.GOMAXPROCS(0)
cpuUserUsage := (cpuTimesAfter[0].User - cpuTimesBefore[0].User) / (float64(1000*threadNum) / 1000)
cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
now := time.Now()
u := cpuUsage{
Time: now,
Usage: cpuUserUsage,
}
CpuUserBuffer = append(CpuUserBuffer, u)
s := cpuUsage{
Time: now,
Usage: cpuUserUsage + cpuSystemUsage,
}
CpuTotalBuffer = append(CpuTotalBuffer, s)
if len(CpuUserBuffer) > 200 {
CpuUserBuffer = CpuUserBuffer[1:]
}
if len(CpuTotalBuffer) > 200 {
CpuTotalBuffer = CpuTotalBuffer[1:]
}
// time.Sleep(1 * time.Second)
}
}