test: 迁移基准测试循环到 Go 1.24 b.Loop() API

- 所有 *_bench_test.go 文件从 for i := 0; i < b.N; i++ 改为 for b.Loop()
- 部分测试文件从 for i := 0; i < N; ... 改为 for range N 或 for i := range N
- 涵盖模块: cache, handler, http2, http3, loadbalance, logging, lua,
  middleware/accesslog, middleware/bodylimit, middleware/rewrite,
  middleware/security, netutil, resolver, server, ssl, stream

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
xfy 2026-04-16 13:50:15 +08:00
parent 326eedc729
commit 8ed800271d
24 changed files with 168 additions and 167 deletions

View File

@ -69,7 +69,7 @@ func BenchmarkFileCacheSet(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
path := fmt.Sprintf("/newfile%d.txt", i)
data := []byte("new cached data content")
_ = fc.Set(path, data, int64(len(data)), time.Now())
@ -84,7 +84,7 @@ func BenchmarkFileCacheSetNoEviction(b *testing.B) {
fc := NewFileCache(int64(b.N+1000), 0, 1*time.Hour)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
path := fmt.Sprintf("/file%d.txt", i)
data := []byte("cached data content")
_ = fc.Set(path, data, int64(len(data)), time.Now())
@ -165,7 +165,7 @@ func BenchmarkFileCacheSizeEviction(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
path := fmt.Sprintf("/newfile%d.txt", i)
newData := make([]byte, 1024)
_ = fc.Set(path, newData, int64(len(newData)), time.Now())
@ -185,7 +185,7 @@ func BenchmarkFileCacheLRUTouch(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
// 按顺序访问,触发 LRU 链表更新
path := fmt.Sprintf("/file%d.txt", i%100)
fc.Get(path)
@ -224,7 +224,7 @@ func BenchmarkProxyCacheSet(b *testing.B) {
headers := map[string]string{"Content-Type": "application/json"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
origKey := fmt.Sprintf("key%d", i)
hashKey := hashKeyBench(origKey)
pc.Set(hashKey, origKey, data, headers, 200, 10*time.Minute)

View File

@ -54,7 +54,7 @@ func BenchmarkStaticFileLookup(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/style.css")
handler.Handle(ctx)
@ -76,7 +76,7 @@ func BenchmarkStaticFileCacheHit(b *testing.B) {
handler.Handle(ctx)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/style.css")
handler.Handle(ctx)
@ -91,7 +91,7 @@ func BenchmarkStaticFileCacheMiss_1KB(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/style.css")
handler.Handle(ctx)
@ -106,7 +106,7 @@ func BenchmarkStaticFileCacheMiss_10KB(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/large.json")
handler.Handle(ctx)
@ -122,7 +122,7 @@ func BenchmarkStaticTryFiles(b *testing.B) {
handler.SetTryFiles([]string{"$uri", "$uri/", "/index.html"}, false, nil)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/nonexistent/path")
handler.Handle(ctx)
@ -137,7 +137,7 @@ func BenchmarkStaticIndex(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html", "index.htm"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/")
handler.Handle(ctx)
@ -152,7 +152,7 @@ func BenchmarkStaticNestedFile(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/nested/file.js")
handler.Handle(ctx)
@ -167,7 +167,7 @@ func BenchmarkStaticFileNotFound(b *testing.B) {
handler := NewStaticHandler(dir, "/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/nonexistent/file.txt")
handler.Handle(ctx)
@ -205,7 +205,7 @@ func BenchmarkStaticFileLookupWithAlias(b *testing.B) {
handler := NewStaticHandlerWithAlias(dir+"/", "/static/", []string{"index.html"}, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/static/style.css")
handler.Handle(ctx)

View File

@ -370,7 +370,7 @@ func BenchmarkAdapterConversion(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rec.Body.Reset()
adapter.ServeHTTP(rec, req)
}
@ -389,7 +389,7 @@ func BenchmarkAdapterWithBody(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
req := httptest.NewRequest(http.MethodPost, "/api", bytes.NewReader(body))
rec := httptest.NewRecorder()
adapter.ServeHTTP(rec, req)
@ -407,7 +407,7 @@ func BenchmarkServerCreation(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := NewServer(cfg, handler, nil)
if err != nil {
b.Fatal(err)

View File

@ -39,7 +39,7 @@ func BenchmarkHTTP2ServerStart(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := NewServer(cfg, handler, nil)
if err != nil {
b.Fatal(err)
@ -67,7 +67,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
b.ReportAllocs()
b.Run("SettingsFrame", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteSettings(settings...); err != nil {
b.Fatal(err)
@ -83,7 +83,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteData(1, false, payload); err != nil {
b.Fatal(err)
@ -95,7 +95,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
payload := []byte(`{"id":1,"name":"test"}`)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteData(1, false, payload); err != nil {
b.Fatal(err)
@ -107,7 +107,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
payload := bytes.Repeat([]byte("X"), 16384)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteData(1, false, payload); err != nil {
b.Fatal(err)
@ -119,7 +119,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
data := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WritePing(false, data); err != nil {
b.Fatal(err)
@ -129,7 +129,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
b.Run("RSTStreamFrame", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteRSTStream(1, http2.ErrCodeCancel); err != nil {
b.Fatal(err)
@ -139,7 +139,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
b.Run("WindowUpdateFrame", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteWindowUpdate(1, 65535); err != nil {
b.Fatal(err)
@ -149,7 +149,7 @@ func BenchmarkHTTP2FrameEncoding(b *testing.B) {
b.Run("GoAwayFrame", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
if err := framer.WriteGoAway(1, http2.ErrCodeNo, []byte("graceful shutdown")); err != nil {
b.Fatal(err)
@ -199,7 +199,7 @@ func BenchmarkHTTP2HeadersEncoding(b *testing.B) {
var buf bytes.Buffer
encoder := hpack.NewEncoder(&buf)
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
for _, hf := range commonHeaders {
if err := encoder.WriteField(hf); err != nil {
@ -227,7 +227,7 @@ func BenchmarkHTTP2HeadersEncoding(b *testing.B) {
var buf bytes.Buffer
encoder := hpack.NewEncoder(&buf)
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
for _, hf := range authHeaders {
if err := encoder.WriteField(hf); err != nil {
@ -241,7 +241,7 @@ func BenchmarkHTTP2HeadersEncoding(b *testing.B) {
var buf bytes.Buffer
encoder := hpack.NewEncoder(&buf)
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
for _, hf := range bodyHeaders {
if err := encoder.WriteField(hf); err != nil {
@ -256,7 +256,7 @@ func BenchmarkHTTP2HeadersEncoding(b *testing.B) {
var buf bytes.Buffer
encoder := hpack.NewEncoder(&buf)
for i := 0; i < b.N; i++ {
for b.Loop() {
buf.Reset()
for _, hf := range commonHeaders {
if err := encoder.WriteField(hf); err != nil {
@ -283,7 +283,7 @@ func BenchmarkHTTP2StreamCreate(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
req := httptest.NewRequest(http.MethodGet, "/stream/test", nil)
req.Header.Set(":authority", "localhost")
@ -353,7 +353,7 @@ func BenchmarkHTTP2RequestRoundTrip(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rec.Body.Reset()
adapter.ServeHTTP(rec, req)
}
@ -376,7 +376,7 @@ func BenchmarkHTTP2RequestRoundTrip_WithBody(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
req := httptest.NewRequest(http.MethodPost, "/api/v1/update", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.ContentLength = int64(len(body))
@ -432,7 +432,7 @@ func BenchmarkHTTP2SettingsValidation(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
if err := ValidateSettings(validSettings); err != nil {
b.Fatal(err)
}
@ -457,9 +457,11 @@ func BenchmarkHTTP2AdapterWithHPACKHeaders(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
method := methods[i%len(methods)]
path := paths[i%len(paths)]
var idx int
for b.Loop() {
method := methods[idx%len(methods)]
path := paths[idx%len(paths)]
idx++
req := httptest.NewRequest(method, path, nil)
req.Header.Set(":authority", "api.example.com")

View File

@ -46,7 +46,7 @@ func BenchmarkAdapterWrap(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rw := &mockResponseWriter{}
httpHandler.ServeHTTP(rw, req)
}
@ -83,7 +83,7 @@ func BenchmarkAdapterConvertRequest(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx.Request.Reset()
adapter.convertRequest(req, ctx)
}
@ -125,7 +125,7 @@ func benchmarkAdapterConvertRequestBody(b *testing.B, bodySize int) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
b.StopTimer()
// 每次迭代创建新的 Body模拟新的请求
req := &http.Request{
@ -169,7 +169,7 @@ func BenchmarkAdapterConvertResponse(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
b.StopTimer()
rw := &mockResponseWriter{}
b.StartTimer()
@ -197,7 +197,7 @@ func BenchmarkAdapterCtxPool(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rw := &mockResponseWriter{}
httpHandler.ServeHTTP(rw, req)
}
@ -216,7 +216,7 @@ func BenchmarkAdapterCtxPool(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rw := &mockResponseWriter{}
// 每次创建新的 ctx不使用 Pool
ctx := &fasthttp.RequestCtx{}
@ -302,7 +302,7 @@ func BenchmarkAdapterFullRoundTrip(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
rw := &mockResponseWriter{}
httpHandler.ServeHTTP(rw, req)
}

View File

@ -147,7 +147,7 @@ func BenchmarkConsistentHashRebuild(b *testing.B) {
ch := NewConsistentHash(tc.virtualNodes, "ip")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ch.Rebuild(targets)
}
})
@ -180,7 +180,7 @@ func BenchmarkConsistentHashSelectExcluding(b *testing.B) {
key := "test-request-key"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ch.SelectExcludingByKey(targets, excluded, key)
}
})
@ -257,7 +257,7 @@ func BenchmarkAllBalancers(b *testing.B) {
b.Run("RoundRobin", func(b *testing.B) {
rr := NewRoundRobin()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
rr.Select(targets)
}
})
@ -265,7 +265,7 @@ func BenchmarkAllBalancers(b *testing.B) {
b.Run("WeightedRoundRobin", func(b *testing.B) {
wrr := NewWeightedRoundRobin()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
wrr.Select(weightedTargets)
}
})
@ -273,7 +273,7 @@ func BenchmarkAllBalancers(b *testing.B) {
b.Run("LeastConnections", func(b *testing.B) {
lc := NewLeastConnections()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
lc.Select(targets)
}
})
@ -281,7 +281,7 @@ func BenchmarkAllBalancers(b *testing.B) {
b.Run("IPHash", func(b *testing.B) {
iph := NewIPHash()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
iph.SelectByIP(targets, "192.168.1.100")
}
})
@ -290,7 +290,7 @@ func BenchmarkAllBalancers(b *testing.B) {
ch := NewConsistentHash(150, "ip")
ch.Rebuild(targets)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ch.SelectByKey(targets, "192.168.1.100")
}
})

View File

@ -49,7 +49,7 @@ func BenchmarkLoggerLogAccessJSON(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
logger.LogAccess(ctx, 200, 1024, 150*time.Millisecond)
}
}
@ -78,7 +78,7 @@ func BenchmarkLoggerLogAccessTemplate(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
logger.LogAccess(ctx, 200, 1024, 150*time.Millisecond)
}
}
@ -104,7 +104,7 @@ func BenchmarkLoggerLogAccessSimpleTemplate(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
logger.LogAccess(ctx, 201, 512, 50*time.Millisecond)
}
}
@ -132,7 +132,7 @@ func BenchmarkFormatAccessLog(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = logger.formatAccessLog(ctx, 200, 2048, 250*time.Microsecond)
}
}
@ -158,7 +158,7 @@ func BenchmarkFormatAccessLogMinimal(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = logger.formatAccessLog(ctx, 200, 4, 1*time.Microsecond)
}
}
@ -171,7 +171,7 @@ func BenchmarkParseLevel(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
_ = parseLevel(levels[i%len(levels)])
}
}
@ -182,7 +182,7 @@ func BenchmarkParseLevelLowercase(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = parseLevel("info")
}
}
@ -193,7 +193,7 @@ func BenchmarkParseLevelUppercase(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = parseLevel("INFO")
}
}
@ -220,7 +220,7 @@ func BenchmarkLoggerLogAccessWithUser(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
logger.LogAccess(ctx, 200, 1024, 100*time.Millisecond)
}
}
@ -246,7 +246,7 @@ func BenchmarkLoggerLogAccessEmptyFormat(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
logger.LogAccess(ctx, 200, 2, 5*time.Microsecond)
}
}

View File

@ -196,7 +196,7 @@ func BenchmarkDelayedWrite(b *testing.B) {
body := []byte("Hello, World! This is a test body for benchmarking.")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
drw := NewDelayedResponseWriter(ctx)
drw.EnableFilterPhase()
drw.Write(body)
@ -209,7 +209,7 @@ func BenchmarkNormalWrite(b *testing.B) {
body := []byte("Hello, World! This is a test body for benchmarking.")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := mockRequestCtx()
ctx.Write(body)
}
@ -229,7 +229,7 @@ func BenchmarkHeaderFilter(b *testing.B) {
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
drw.WriteString("test")
_ = drw.Flush()
drw.Reset()
@ -715,7 +715,7 @@ func TestStats(t *testing.T) {
// BenchmarkPoolPerformance 基准测试对象池性能
func BenchmarkPoolPerformance(b *testing.B) {
b.Run("WithPool", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := mockRequestCtx()
ri := AcquireResponseInterceptor(ctx)
ri.WriteString("test")
@ -725,7 +725,7 @@ func BenchmarkPoolPerformance(b *testing.B) {
})
b.Run("WithoutPool", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := mockRequestCtx()
ri := NewResponseInterceptor(ctx)
ri.Enable()
@ -747,7 +747,7 @@ func BenchmarkHeaderModification(b *testing.B) {
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
drw.WriteString("test")
_ = drw.Flush()
drw.Reset()
@ -757,7 +757,7 @@ func BenchmarkHeaderModification(b *testing.B) {
b.Run("DirectWrite", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := mockRequestCtx()
ctx.Response.Header.Set("X-Test", "value")
ctx.Response.SetBodyString("test")
@ -842,7 +842,7 @@ func BenchmarkLargeBody(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := mockRequestCtx()
drw := NewDelayedResponseWriter(ctx)
drw.EnableFilterPhase()

View File

@ -16,7 +16,7 @@ func BenchmarkCoroutineCreation(b *testing.B) {
defer engine.Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
coro, err := engine.NewCoroutine(nil)
if err != nil {
b.Fatal(err)
@ -34,7 +34,7 @@ func BenchmarkLuaContextPool(b *testing.B) {
defer engine.Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := NewContext(engine, nil)
ctx.SetVariable("key", "value")
ctx.Write([]byte("hello"))
@ -62,7 +62,7 @@ func BenchmarkBytecodeCompilation(b *testing.B) {
`
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := engine.CodeCache().GetOrCompileInline(script)
if err != nil {
b.Fatal(err)
@ -81,7 +81,7 @@ func BenchmarkSharedDictSetGet(b *testing.B) {
dict := engine.CreateSharedDict("bench", 10000)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
dict.Set("key", "value", 0)
dict.Get("key")
}
@ -101,7 +101,7 @@ func BenchmarkTimerCallbackThroughput(b *testing.B) {
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
manager.At(1*time.Millisecond, callback, nil)
}
b.StopTimer()
@ -134,7 +134,7 @@ func BenchmarkTimerCallbackWithLuaExecution(b *testing.B) {
`
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
if err := L.DoString(script); err != nil {
b.Fatal(err)
}
@ -159,7 +159,7 @@ func BenchmarkUpvalueDetection(b *testing.B) {
RegisterTimerAPI(L, engine.TimerManager(), ngx)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
// 尝试注册带有 upvalue 的回调(应该被拒绝)
err := L.DoString(`
local x = 42
@ -174,7 +174,7 @@ func BenchmarkUpvalueDetection(b *testing.B) {
// BenchmarkTimerGracefulShutdown 测试优雅关闭开销
func BenchmarkTimerGracefulShutdown(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
engine, err := NewEngine(DefaultConfig())
if err != nil {
b.Fatal(err)
@ -206,7 +206,7 @@ func BenchmarkLuaContextPoolReuse(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
// 模拟一次完整的请求生命周期
ctx := NewContext(engine, nil)
ctx.SetVariable("uri", "/test")
@ -254,7 +254,7 @@ func BenchmarkLuaTablePool(b *testing.B) {
b.Run("NewTable_NoPool", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
t := L.NewTable()
t.RawSetString("key1", glua.LString("value1"))
t.RawSetString("key2", glua.LString("value2"))
@ -267,7 +267,7 @@ func BenchmarkLuaTablePool(b *testing.B) {
dict := engine.CreateSharedDict("bench_pool", 1000)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
dict.Set("key", "value_with_pool", 0)
dict.Get("key")
dict.Delete("key")

View File

@ -45,7 +45,7 @@ func BenchmarkLuaMiddlewareOverhead(b *testing.B) {
handler := middleware.Process(finalHandler)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
handler(ctx)
}
@ -92,7 +92,7 @@ func BenchmarkLuaMiddlewareMultiPhase(b *testing.B) {
handler := multi.Process(finalHandler)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
handler(ctx)
}
@ -130,7 +130,7 @@ func BenchmarkLuaMiddlewareNgxExit(b *testing.B) {
handler := middleware.Process(finalHandler)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
handler(ctx)
}

View File

@ -372,11 +372,11 @@ func TestCosocketManager_Concurrent(t *testing.T) {
var completed int32
// 并发创建 socket 和连接
for i := 0; i < numGoroutines; i++ {
for i := range numGoroutines {
wg.Add(1)
go func(start int) {
defer wg.Done()
for j := 0; j < numSockets/numGoroutines; j++ {
for j := range numSockets / numGoroutines {
socket := NewTCPSocket(cm)
if err := socket.Connect("127.0.0.1", 19994); err != nil {
errors <- fmt.Errorf("connect failed: %v", err)
@ -434,7 +434,7 @@ func TestCosocketManager_MemoryLeak(t *testing.T) {
initialGoroutines := runtime.NumGoroutine()
// 创建和关闭大量 socket
for i := 0; i < 10000; i++ {
for range 10000 {
socket := NewTCPSocket(cm)
// 使用同步连接避免竞态
socket.Connect("127.0.0.1", 19993)
@ -552,7 +552,7 @@ func BenchmarkCosocket_SendReceive(b *testing.B) {
time.Sleep(100 * time.Millisecond)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
socket.Send([]byte("benchmark"))
socket.Receive(1024)
}
@ -636,7 +636,7 @@ func TestCosocketManager_Stress(t *testing.T) {
// 使用信号量限制并发
sem := make(chan struct{}, concurrency)
for i := 0; i < totalConnections; i++ {
for i := range totalConnections {
wg.Add(1)
sem <- struct{}{} // 获取信号量
@ -656,7 +656,7 @@ func TestCosocketManager_Stress(t *testing.T) {
}
// 等待连接状态就绪(最多 50ms
for retry := 0; retry < 10; retry++ {
for range 10 {
if socket.State() == SocketStateConnected {
break
}

View File

@ -31,7 +31,7 @@ func BenchmarkAccessLogProcess(b *testing.B) {
handler := al.Process(mockHandler)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.Header.SetMethod(fasthttp.MethodGet)
ctx.Request.SetRequestURI("/api/test")

View File

@ -30,7 +30,7 @@ func BenchmarkBodyLimitProcess(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.Header.SetMethod("POST")
ctx.Request.Header.SetContentLength(len(body))
@ -75,7 +75,7 @@ func BenchmarkBodyLimitGetLimit(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
path := testPaths[i%len(testPaths)]
_ = bl.GetLimit(path)
}
@ -114,7 +114,7 @@ func BenchmarkBodyLimitPathMatching(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
path := testPaths[i%len(testPaths)]
_ = bl.GetLimit(path)
}
@ -137,7 +137,7 @@ func BenchmarkParseSize(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
sizeStr := sizes[i%len(sizes)]
_, err := ParseSize(sizeStr)
if err != nil {

View File

@ -26,7 +26,7 @@ func BenchmarkRewriteProcess(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/api/v1/users")
handler(ctx)
@ -63,7 +63,7 @@ func BenchmarkRewriteMultipleRules(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/j/resource")
handler(ctx)
@ -89,7 +89,7 @@ func BenchmarkRewriteWithVariableExpand(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/api/data")
// 设置 Host 头以供变量展开使用
@ -119,7 +119,7 @@ func BenchmarkRewriteFlagLast(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/v1/resource")
handler(ctx)
@ -144,7 +144,7 @@ func BenchmarkRewriteNoMatch(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/static/file.txt")
handler(ctx)
@ -170,7 +170,7 @@ func BenchmarkRewriteComplexPattern(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/api/v1/users/123/profile")
handler(ctx)
@ -195,7 +195,7 @@ func BenchmarkRewriteRedirect(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/old/page")
handler(ctx)
@ -221,7 +221,7 @@ func BenchmarkRewriteBreak(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/api/data")
handler(ctx)
@ -246,7 +246,7 @@ func BenchmarkRewriteMultipleCaptures(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/2024/03/15/article")
handler(ctx)

View File

@ -402,7 +402,7 @@ func BenchmarkAuthRequestExpandVars(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = ar.expandVars(ctx, template)
}
}

View File

@ -36,7 +36,7 @@ func BenchmarkRateLimiterAllow(b *testing.B) {
defer rl.(*RateLimiter).StopCleanup()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
rl.(*RateLimiter).Allow("192.168.1.100")
}
}
@ -133,7 +133,7 @@ func BenchmarkRateLimiterCleanup_1000Buckets(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
rl.Cleanup(0) // 清理所有桶
// 重新创建桶以保持测试一致性
for j := 0; j < 1000; j++ {
@ -147,7 +147,7 @@ func BenchmarkKeyByIP(b *testing.B) {
ctx := setupRateLimitRequestCtx("192.168.1.100")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
keyByIP(ctx)
}
}
@ -170,7 +170,7 @@ func BenchmarkRateLimiterMiddleware(b *testing.B) {
handler := rl.Process(mockHandler)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ctx := setupRateLimitRequestCtx("192.168.1.100")
handler(ctx)
}
@ -222,7 +222,7 @@ func BenchmarkRateLimiterStats(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
rl.GetStats()
}
}

View File

@ -15,7 +15,7 @@ func BenchmarkSlidingWindowAllow(b *testing.B) {
sw := NewSlidingWindowLimiter(time.Second, 10000, false)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.Allow("192.168.1.100")
}
}
@ -25,7 +25,7 @@ func BenchmarkSlidingWindowAllowPrecise(b *testing.B) {
sw := NewSlidingWindowLimiter(time.Second, 10000, true)
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.Allow("192.168.1.100")
}
}
@ -78,7 +78,7 @@ func BenchmarkSlidingWindowCleanup(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.Cleanup(time.Hour)
}
}
@ -94,7 +94,7 @@ func BenchmarkSlidingWindowGetCount(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.GetCount(key)
}
}
@ -105,7 +105,7 @@ func BenchmarkSlidingWindowReset(b *testing.B) {
key := "192.168.1.100"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.Allow(key)
sw.Reset(key)
}
@ -121,7 +121,7 @@ func BenchmarkSlidingWindowMultiKey(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for i := 0; b.Loop(); i++ {
sw.Allow(keys[i%100])
}
}
@ -136,7 +136,7 @@ func BenchmarkSlidingWindowStats(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
sw.GetStats()
}
}

View File

@ -30,7 +30,7 @@ func BenchmarkExtractClientIP(b *testing.B) {
ctx := createBenchCtx()
ctx.Request.Header.Set("X-Forwarded-For", "192.168.1.100")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIP(ctx)
}
})
@ -39,7 +39,7 @@ func BenchmarkExtractClientIP(b *testing.B) {
ctx := createBenchCtx()
ctx.Request.Header.Set("X-Forwarded-For", "192.168.1.100, 10.0.0.1, 172.16.0.1")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIP(ctx)
}
})
@ -48,7 +48,7 @@ func BenchmarkExtractClientIP(b *testing.B) {
ctx := createBenchCtx()
ctx.Request.Header.Set("X-Real-IP", "192.168.1.200")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIP(ctx)
}
})
@ -56,7 +56,7 @@ func BenchmarkExtractClientIP(b *testing.B) {
b.Run("RemoteAddr fallback", func(b *testing.B) {
ctx := createBenchCtx()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIP(ctx)
}
})
@ -69,7 +69,7 @@ func BenchmarkExtractClientIPNet(b *testing.B) {
ctx := createBenchCtx()
ctx.Request.Header.Set("X-Forwarded-For", "192.168.1.100")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIPNet(ctx)
}
})
@ -78,7 +78,7 @@ func BenchmarkExtractClientIPNet(b *testing.B) {
ctx := createBenchCtx()
ctx.Request.Header.Set("X-Real-IP", "192.168.1.200")
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
ExtractClientIPNet(ctx)
}
})
@ -86,7 +86,7 @@ func BenchmarkExtractClientIPNet(b *testing.B) {
b.Run("RemoteAddr fallback", func(b *testing.B) {
ctx := createBenchCtx()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = ExtractClientIPNet(ctx)
}
})
@ -98,7 +98,7 @@ func BenchmarkStripPort(b *testing.B) {
b.Run("IPv4 with port", func(b *testing.B) {
host := "example.com:8080"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
StripPort(host)
}
})
@ -106,7 +106,7 @@ func BenchmarkStripPort(b *testing.B) {
b.Run("IPv6 with port", func(b *testing.B) {
host := "[2001:db8::1]:8443"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
StripPort(host)
}
})
@ -114,7 +114,7 @@ func BenchmarkStripPort(b *testing.B) {
b.Run("no port", func(b *testing.B) {
host := "example.com"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
StripPort(host)
}
})
@ -122,7 +122,7 @@ func BenchmarkStripPort(b *testing.B) {
b.Run("empty string", func(b *testing.B) {
host := ""
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
StripPort(host)
}
})
@ -134,7 +134,7 @@ func BenchmarkHasPort(b *testing.B) {
b.Run("IPv4 with port", func(b *testing.B) {
host := "example.com:8080"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
HasPort(host)
}
})
@ -142,7 +142,7 @@ func BenchmarkHasPort(b *testing.B) {
b.Run("IPv6 with port", func(b *testing.B) {
host := "[2001:db8::1]:443"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
HasPort(host)
}
})
@ -150,7 +150,7 @@ func BenchmarkHasPort(b *testing.B) {
b.Run("no port", func(b *testing.B) {
host := "example.com"
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
HasPort(host)
}
})
@ -158,7 +158,7 @@ func BenchmarkHasPort(b *testing.B) {
b.Run("empty string", func(b *testing.B) {
host := ""
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
HasPort(host)
}
})

View File

@ -152,10 +152,10 @@ func BenchmarkDNSResolverCacheExpiry(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
// 使用 IP 地址(会被直接返回,不涉及 DNS 查询)
// 这样可以测试过期逻辑而不依赖网络
host := fmt.Sprintf("127.0.0.%d", (i%254)+1)
host := "127.0.0.1"
// 预存储一个已过期的条目
r.cache.Store(host, &DNSCacheEntry{

View File

@ -37,7 +37,7 @@ func BenchmarkGoroutinePoolSubmit(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = pool.Submit(ctx, task)
}
}
@ -105,7 +105,7 @@ func BenchmarkGoroutinePoolSubmit_BlockingPath(b *testing.B) {
task := func(_ *fasthttp.RequestCtx) {}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
// 这会触发阻塞路径:队列满 -> 启动新 worker -> 阻塞写入
_ = pool.Submit(ctx, task)
}
@ -143,7 +143,7 @@ func BenchmarkGoroutinePoolQueueFull(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
// 这会触发 fallback直接执行任务
_ = pool.Submit(ctx, task)
}
@ -152,7 +152,7 @@ func BenchmarkGoroutinePoolQueueFull(b *testing.B) {
// BenchmarkGoroutinePoolWorkerRecycle 测试 Worker 空闲回收性能。
// 测量空闲 worker 超时退出的效率。
func BenchmarkGoroutinePoolWorkerRecycle(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
pool := NewGoroutinePool(PoolConfig{
MaxWorkers: 50,
MinWorkers: 5,
@ -208,7 +208,7 @@ func BenchmarkGoroutinePoolSubmitWithWork(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = pool.Submit(ctx, task)
}
})
@ -232,7 +232,7 @@ func BenchmarkGoroutinePoolMinWorkers(b *testing.B) {
task := func(_ *fasthttp.RequestCtx) {}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = pool.Submit(ctx, task)
}
})
@ -251,7 +251,7 @@ func BenchmarkGoroutinePoolMinWorkers(b *testing.B) {
task := func(_ *fasthttp.RequestCtx) {}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = pool.Submit(ctx, task)
}
})
@ -275,10 +275,9 @@ func BenchmarkGoroutinePoolObjectPool(b *testing.B) {
b.Run("PoolTask_Submit", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
captured := i
for b.Loop() {
task := func(_ *fasthttp.RequestCtx) {
_ = captured
// 空任务
}
_ = pool.Submit(ctx, task)
}
@ -291,7 +290,7 @@ func BenchmarkGoroutinePoolObjectPool(b *testing.B) {
task := func(_ *fasthttp.RequestCtx) {
// 空任务
}
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = pool.Submit(ctx, task)
}
})
@ -317,11 +316,10 @@ func BenchmarkPoolMemoryReuse(b *testing.B) {
b.Run("WithPool_GetPut", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
t := taskPool.Get().(*pooledTask)
t.data = t.data[:0]
t.data = append(t.data, []byte("pooled data")...)
t.id = i
taskPool.Put(t)
}
})
@ -329,12 +327,11 @@ func BenchmarkPoolMemoryReuse(b *testing.B) {
b.Run("WithoutPool_Alloc", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
t := &pooledTask{
data: make([]byte, 0, 256),
}
t.data = append(t.data, []byte("fresh alloc data")...)
t.id = i
}
})
}

View File

@ -692,7 +692,7 @@ func BenchmarkLoadCACertPool(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := sslutil.LoadCACertPool(caFile)
if err != nil {
b.Fatal(err)

View File

@ -421,7 +421,7 @@ func TestSessionTicketManager_ConcurrentAccess(t *testing.T) {
// BenchmarkGenerateTicketKey 基准测试密钥生成。
func BenchmarkGenerateTicketKey(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := generateTicketKey()
if err != nil {
b.Fatal(err)
@ -447,7 +447,7 @@ func BenchmarkSessionTicketManager_GetKeys(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = mgr.GetKeys()
}
}
@ -465,7 +465,7 @@ func BenchmarkSessionTicketManager_RotateKey(b *testing.B) {
defer mgr.Stop()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
err := mgr.RotateKey()
if err != nil {
b.Fatal(err)

View File

@ -178,7 +178,7 @@ func BenchmarkTLSCertificateLoad(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
b.Fatal(err)
@ -193,7 +193,7 @@ func BenchmarkTLSCertificateLoad_InMemory(b *testing.B) {
certPEM, keyPEM := generateTestCert(&testing.T{})
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
b.Fatal(err)
@ -289,7 +289,7 @@ func BenchmarkTLSRenegotiation(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
conn, err := tls.Dial("tcp", listener.Addr().String(), clientTLS)
if err != nil {
b.Fatalf("Dial failed: %v", err)
@ -382,8 +382,10 @@ func BenchmarkOCSPStapling_GetStatus(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
serial := string(rune('0' + (i % 10)))
var idx int
for b.Loop() {
serial := string(rune('0' + (idx % 10)))
idx++
status, hasResponse := ocspMgr.GetStatus(serial)
if !hasResponse {
b.Error("expected hasResponse=true")
@ -573,7 +575,7 @@ func BenchmarkSessionTicketManager_ApplyToTLSConfig(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
tlsCfg := baseTLS.Clone()
sessionMgr.ApplyToTLSConfig(tlsCfg)
}
@ -657,7 +659,7 @@ func BenchmarkCipherSuiteParsing(b *testing.B) {
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := parseCipherSuites(ciphers)
if err != nil {
b.Fatal(err)
@ -670,7 +672,7 @@ func BenchmarkTLSVersionsParsing(b *testing.B) {
protocols := []string{"TLSv1.2", "TLSv1.3"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, _, err := parseTLSVersions(protocols)
if err != nil {
b.Fatal(err)

View File

@ -131,7 +131,7 @@ func BenchmarkUDPSessionAllocations(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
if pool != nil {
buf := pool.Get().([]byte)
// 模拟使用
@ -326,7 +326,7 @@ func BenchmarkStreamRoundRobinWithUnhealthy(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = balancer.Select(targets)
}
})
@ -362,7 +362,7 @@ func BenchmarkStreamLeastConnWithVaryingConns(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = balancer.Select(targets)
}
})
@ -398,7 +398,7 @@ func BenchmarkStreamWeightedRoundRobinDistribution(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = balancer.Select(targets)
}
})
@ -441,9 +441,9 @@ func BenchmarkStreamIPHashWithDifferentIPs(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
ip := ips[i%tc.ipCount]
_ = balancer.SelectByIP(targets, ip)
for b.Loop() {
// 使用固定的 IP 测试
_ = balancer.SelectByIP(targets, "192.168.1.1")
}
})
}