From 397181429eaf75856b445d973735746335bab506 Mon Sep 17 00:00:00 2001 From: Alex Yang Date: Tue, 25 Nov 2025 18:02:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DCPU=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E7=8E=87=E4=B8=BA=E9=9A=8F=E6=9C=BA=E6=A8=A1=E6=8B=9F=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dns/server.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/dns/server.go b/dns/server.go index c81a84e..b5d9e55 100644 --- a/dns/server.go +++ b/dns/server.go @@ -758,12 +758,19 @@ func (s *Server) startCpuUsageMonitor() { var memStats runtime.MemStats runtime.ReadMemStats(&memStats) + // 存储上一次的CPU时间统计 + var prevIdle, prevTotal uint64 + for { select { case <-ticker.C: - // 使用简单的CPU使用率模拟,实际生产环境可使用更精确的库 - // 这里生成一个随机的CPU使用率值(10%-70%之间) - cpuUsage := 10.0 + float64(time.Now().Unix()%60)/100.0*60.0 + // 获取真实的系统级CPU使用率 + cpuUsage, err := getSystemCpuUsage(&prevIdle, &prevTotal) + if err != nil { + // 如果获取失败,使用默认值 + cpuUsage = 0.0 + logger.Error("获取系统CPU使用率失败", "error", err) + } s.updateStats(func(stats *Stats) { 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 启动自动保存功能 func (s *Server) startAutoSave() { if s.config.StatsFile == "" || s.config.SaveInterval <= 0 {