mirror of
https://github.com/0xJacky/nginx-ui.git
synced 2025-05-11 18:35:51 +02:00
use goroutine to record cpu usage
This commit is contained in:
parent
16a3d02d9c
commit
897c3cddcd
7 changed files with 134 additions and 63 deletions
|
@ -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,
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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
45
server/tool/cpu_usage.go
Normal 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)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue