From 386e80914fa3b09c7544b1e714b232a2542d3851 Mon Sep 17 00:00:00 2001 From: wood chen Date: Sun, 1 Dec 2024 00:46:16 +0800 Subject: [PATCH] refactor(monitoring, public): streamline latency formatting and metrics logging - Removed the obsolete formatLatency function from metrics.go to simplify the codebase. - Updated the HTML to utilize the new latency formatting method, ensuring consistent display of average latency metrics. - Enhanced the LogRequest function to accurately calculate and update average latency based on request counts, improving metrics accuracy. --- monitoring/metrics.go | 26 ++++++++------------------ public/index.html | 2 +- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/monitoring/metrics.go b/monitoring/metrics.go index 905a737..26124e2 100644 --- a/monitoring/metrics.go +++ b/monitoring/metrics.go @@ -2,7 +2,6 @@ package monitoring import ( "encoding/json" - "fmt" "runtime" "strings" "sync" @@ -101,16 +100,6 @@ func CollectMetrics() *SystemMetrics { return &metrics } -func formatLatency(microseconds float64) string { - if microseconds < 1000 { - return fmt.Sprintf("%.3fµs", microseconds) - } - if microseconds < 1000000 { - return fmt.Sprintf("%.3fms", microseconds/1000) - } - return fmt.Sprintf("%.3fs", microseconds/1000000) -} - func LogRequest(log RequestLog) { metrics.RequestCount.Add(1) @@ -142,14 +131,15 @@ func LogRequest(log RequestLog) { if len(metrics.RecentRequests) > 100 { metrics.RecentRequests = metrics.RecentRequests[:100] } - } -} -// 添加字符串池 -var stringPool = sync.Pool{ - New: func() interface{} { - return new(string) - }, + // 更新平均延迟(保持微秒单位) + count := metrics.RequestCount.Load() + if count > 1 { + metrics.AverageLatency = (metrics.AverageLatency*(float64(count)-1) + log.Latency) / float64(count) + } else { + metrics.AverageLatency = log.Latency + } + } } // 添加分段锁结构 diff --git a/public/index.html b/public/index.html index 7efe7ee..fc31017 100644 --- a/public/index.html +++ b/public/index.html @@ -275,7 +275,7 @@

性能指标

总请求数:${metrics.request_count}
-
平均延迟:${metrics.average_latency.toFixed(2)}ms
+
平均延迟:${formatLatency(metrics.average_latency)}