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 <lightclient@protonmail.com>
This commit is contained in:
cui 2025-09-20 07:05:21 +08:00 committed by GitHub
parent 3ebb1431d3
commit 9b1896bfb5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 10 deletions

View file

@ -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)
}
}

View file

@ -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()
}