From 9b1896bfb576cb68df7cff801b9b1bf4d79e9d97 Mon Sep 17 00:00:00 2001 From: cui Date: Sat, 20 Sep 2025 07:05:21 +0800 Subject: [PATCH] log: using testing.B.Loop (#32663) before: go test -run=^$ -bench=. ./log -timeout=1h 12.19s user 2.19s system 89% cpu 16.025 total after: go test -run=^$ -bench=. ./log -timeout=1h 10.64s user 1.53s system 89% cpu 13.607 total --------- Co-authored-by: lightclient --- log/format_test.go | 4 ++-- log/logger_test.go | 17 +++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/log/format_test.go b/log/format_test.go index d4c1df4abc..bb740ceb84 100644 --- a/log/format_test.go +++ b/log/format_test.go @@ -10,7 +10,7 @@ var sink []byte func BenchmarkPrettyInt64Logfmt(b *testing.B) { buf := make([]byte, 100) b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { sink = appendInt64(buf, rand.Int63()) } } @@ -18,7 +18,7 @@ func BenchmarkPrettyInt64Logfmt(b *testing.B) { func BenchmarkPrettyUint64Logfmt(b *testing.B) { buf := make([]byte, 100) b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { sink = appendUint64(buf, rand.Uint64(), false) } } diff --git a/log/logger_test.go b/log/logger_test.go index 3ec6d2e19c..dae8497204 100644 --- a/log/logger_test.go +++ b/log/logger_test.go @@ -70,9 +70,10 @@ func TestJSONHandler(t *testing.T) { func BenchmarkTraceLogging(b *testing.B) { SetDefault(NewLogger(NewTerminalHandler(io.Discard, true))) - b.ResetTimer() - for i := 0; i < b.N; i++ { + i := 0 + for b.Loop() { Trace("a message", "v", i) + i++ } } @@ -99,8 +100,8 @@ func benchmarkLogger(b *testing.B, l Logger) { err = errors.New("oh nooes it's crap") ) b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { + i := 0 + for b.Loop() { l.Info("This is a message", "foo", int16(i), "bytes", bb, @@ -109,8 +110,8 @@ func benchmarkLogger(b *testing.B, l Logger) { "bigint", bigint, "nilbig", nilbig, "err", err) + i++ } - b.StopTimer() } func TestLoggerOutput(t *testing.T) { @@ -161,18 +162,18 @@ const termTimeFormat = "01-02|15:04:05.000" func BenchmarkAppendFormat(b *testing.B) { var now = time.Now() b.Run("fmt time.Format", func(b *testing.B) { - for i := 0; i < b.N; i++ { + for b.Loop() { fmt.Fprintf(io.Discard, "%s", now.Format(termTimeFormat)) } }) b.Run("time.AppendFormat", func(b *testing.B) { - for i := 0; i < b.N; i++ { + for b.Loop() { now.AppendFormat(nil, termTimeFormat) } }) var buf = new(bytes.Buffer) b.Run("time.Custom", func(b *testing.B) { - for i := 0; i < b.N; i++ { + for b.Loop() { writeTimeTermFormat(buf, now) buf.Reset() }