修复CPU使用率为随机模拟数据
This commit is contained in:
@@ -758,12 +758,19 @@ func (s *Server) startCpuUsageMonitor() {
|
|||||||
var memStats runtime.MemStats
|
var memStats runtime.MemStats
|
||||||
runtime.ReadMemStats(&memStats)
|
runtime.ReadMemStats(&memStats)
|
||||||
|
|
||||||
|
// 存储上一次的CPU时间统计
|
||||||
|
var prevIdle, prevTotal uint64
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
// 使用简单的CPU使用率模拟,实际生产环境可使用更精确的库
|
// 获取真实的系统级CPU使用率
|
||||||
// 这里生成一个随机的CPU使用率值(10%-70%之间)
|
cpuUsage, err := getSystemCpuUsage(&prevIdle, &prevTotal)
|
||||||
cpuUsage := 10.0 + float64(time.Now().Unix()%60)/100.0*60.0
|
if err != nil {
|
||||||
|
// 如果获取失败,使用默认值
|
||||||
|
cpuUsage = 0.0
|
||||||
|
logger.Error("获取系统CPU使用率失败", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
s.updateStats(func(stats *Stats) {
|
s.updateStats(func(stats *Stats) {
|
||||||
stats.CpuUsage = cpuUsage
|
stats.CpuUsage = cpuUsage
|
||||||
@@ -774,6 +781,45 @@ func (s *Server) startCpuUsageMonitor() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getSystemCpuUsage 获取系统CPU使用率
|
||||||
|
func getSystemCpuUsage(prevIdle, prevTotal *uint64) (float64, error) {
|
||||||
|
// 读取/proc/stat文件获取CPU统计信息
|
||||||
|
file, err := os.Open("/proc/stat")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
var cpuUser, cpuNice, cpuSystem, cpuIdle, cpuIowait, cpuIrq, cpuSoftirq, cpuSteal uint64
|
||||||
|
_, err = fmt.Fscanf(file, "cpu %d %d %d %d %d %d %d %d",
|
||||||
|
&cpuUser, &cpuNice, &cpuSystem, &cpuIdle, &cpuIowait, &cpuIrq, &cpuSoftirq, &cpuSteal)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算总的CPU时间
|
||||||
|
total := cpuUser + cpuNice + cpuSystem + cpuIdle + cpuIowait + cpuIrq + cpuSoftirq + cpuSteal
|
||||||
|
idle := cpuIdle + cpuIowait
|
||||||
|
|
||||||
|
// 第一次调用时,只初始化值,不计算使用率
|
||||||
|
if *prevTotal == 0 || *prevIdle == 0 {
|
||||||
|
*prevIdle = idle
|
||||||
|
*prevTotal = total
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算CPU使用率
|
||||||
|
idleDelta := idle - *prevIdle
|
||||||
|
totalDelta := total - *prevTotal
|
||||||
|
utilization := float64(totalDelta-idleDelta) / float64(totalDelta) * 100
|
||||||
|
|
||||||
|
// 更新上一次的值
|
||||||
|
*prevIdle = idle
|
||||||
|
*prevTotal = total
|
||||||
|
|
||||||
|
return utilization, nil
|
||||||
|
}
|
||||||
|
|
||||||
// startAutoSave 启动自动保存功能
|
// startAutoSave 启动自动保存功能
|
||||||
func (s *Server) startAutoSave() {
|
func (s *Server) startAutoSave() {
|
||||||
if s.config.StatsFile == "" || s.config.SaveInterval <= 0 {
|
if s.config.StatsFile == "" || s.config.SaveInterval <= 0 {
|
||||||
|
|||||||
Reference in New Issue
Block a user