Files
loggerx/loggerx_bench_test.go
T
2026-09-13 21:53:37 +08:00

79 lines
1.8 KiB
Go

package loggerx_test
import (
"context"
"io"
"testing"
"time"
"github.com/yuninks/loggerx"
)
func benchLogger(b *testing.B, opts ...loggerx.Option) *loggerx.Logger {
b.Helper()
// 预热时区:Windows 上 time.Local 首次使用会去读注册表(一次性、很贵),
// 不预热会把这笔初始化成本摊到单次日志耗时里
_, _ = time.Now().In(time.Local).Zone()
opts = append([]loggerx.Option{loggerx.SetDir(b.TempDir())}, opts...)
l := loggerx.NewLogger(context.Background(), opts...)
b.Cleanup(func() { _ = l.Close() })
return l
}
// 同步写入:每条都进缓冲(32KB 才落盘一次)
func BenchmarkWriteSync(b *testing.B) {
l := benchLogger(b)
ctx := context.Background()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Infof(ctx, "hello %d", i)
}
}
// 异步写入
func BenchmarkWriteAsync(b *testing.B) {
l := benchLogger(b, loggerx.SetWriteAsync())
al := l.WriteAsync()
ctx := context.Background()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
al.Infof(ctx, "hello %d", i)
}
}
// 并行写入(16 核)
func BenchmarkWriteParallel(b *testing.B) {
l := benchLogger(b)
ctx := context.Background()
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
l.Infof(ctx, "hello parallel")
}
})
}
// 关闭 goroutine id、关掉文件输出:看纯格式化开销
func BenchmarkFormatOnly(b *testing.B) {
l := benchLogger(b, loggerx.SetPrintFile(false), loggerx.SetExtraDriver(io.Discard), loggerx.SetGID(false))
ctx := context.Background()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Infof(ctx, "hello %d", i)
}
}
// 默认(含 goroutine id + 写文件)
func BenchmarkDefault(b *testing.B) {
l := benchLogger(b)
ctx := context.Background()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Info(ctx, "hello")
}
}