性能优化: 热路径零分配, 自适应池CAS无锁化, 锁外计算

- port_scan: fmt.Sprintf→JoinHostPort+fmtPort零分配地址格式化 (2.5x)
- port_scan: strings.ToLower→containsFold零分配大小写不敏感匹配 (2.5x)
- port_scan: slidingWindowSchedule修复semaphore泄漏bug
- service_probe: readFromConn预分配4KB缓冲区消除扩容
- adaptive_pool: maybeAdjust用atomic CAS代替持锁检查, 99%免锁
- adaptive_timeout: Timeout锁外计算均值/标准差, 只锁缓存更新
- 新增perf_bench_test.go基准测试验证所有优化
This commit is contained in:
ZacharyZcR
2026-05-18 06:11:10 +08:00
parent 639298b7c8
commit 7063027acf
6 changed files with 226 additions and 44 deletions
+25 -7
View File
@@ -46,16 +46,18 @@ func (a *AdaptiveTimeout) Record(rtt time.Duration) {
// Timeout 获取当前推荐超时值
// 样本不足时返回 maxTO(冷启动)
// 锁外执行均值/标准差计算,减少锁持有时间
func (a *AdaptiveTimeout) Timeout() time.Duration {
a.mu.Lock()
defer a.mu.Unlock()
if a.count < a.warmup {
a.mu.Unlock()
return a.maxTO
}
if !a.dirty {
return a.cachedTO
cached := a.cachedTO
a.mu.Unlock()
return cached
}
n := a.size
@@ -63,15 +65,27 @@ func (a *AdaptiveTimeout) Timeout() time.Duration {
n = a.count
}
// 拷贝样本到本地,释放锁后再计算
localSamples := make([]float64, n)
start := a.pos % a.size
if a.count < a.size {
copy(localSamples, a.samples[:n])
} else {
copy(localSamples[:a.size-start], a.samples[start:])
copy(localSamples[a.size-start:], a.samples[:start])
}
a.mu.Unlock()
// 锁外计算
var sum float64
for i := 0; i < n; i++ {
sum += a.samples[i]
for _, s := range localSamples {
sum += s
}
mean := sum / float64(n)
var variance float64
for i := 0; i < n; i++ {
d := a.samples[i] - mean
for _, s := range localSamples {
d := s - mean
variance += d * d
}
stddev := math.Sqrt(variance / float64(n))
@@ -86,7 +100,11 @@ func (a *AdaptiveTimeout) Timeout() time.Duration {
to = a.maxTO
}
// 短暂加锁更新缓存
a.mu.Lock()
a.cachedTO = to
a.dirty = false
a.mu.Unlock()
return to
}