Skip to content

Commit

Permalink
Add a benchmark
Browse files Browse the repository at this point in the history
Add a benchmark that measures the performance of the writer when writes are
split across multiple lines, as well as when it's one log per write.

```
name             time/op
Writer/single-4  652ns ± 4%
Writer/splits-4  736ns ±11%

name             alloc/op
Writer/single-4  16.0B ± 0%
Writer/splits-4  16.0B ± 0%

name             allocs/op
Writer/single-4   2.00 ± 0%
Writer/splits-4   2.00 ± 0%
```
  • Loading branch information
abhinav committed Jun 24, 2021
1 parent 0072bc4 commit 48f2f4d
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions zapio/writer_test.go
Expand Up @@ -156,3 +156,60 @@ func TestWriter(t *testing.T) {
})
}
}

func BenchmarkWriter(b *testing.B) {
tests := []struct {
name string
writes [][]byte
}{
{
name: "single",
writes: [][]byte{
[]byte("foobar\n"),
[]byte("bazqux\n"),
},
},
{
name: "splits",
writes: [][]byte{
[]byte("foo"),
[]byte("bar\nbaz"),
[]byte("qux\n"),
},
},
}

writer := Writer{
Log: zap.New(new(partiallyNopCore)),
Level: zapcore.DebugLevel,
}

for _, tt := range tests {
b.Run(tt.name, func(b *testing.B) {
b.ResetTimer()

for i := 0; i < b.N; i++ {
for _, bs := range tt.writes {
writer.Write(bs)
}
}
})
}
}

// partiallyNopCore behaves exactly like NopCore except it always returns true
// for whether the provided level is enabled, and accepts all Check requests.
//
// This lets us measure the overhead of the writer without measuring the cost
// of logging.
type partiallyNopCore struct{}

func (*partiallyNopCore) Enabled(zapcore.Level) bool { return true }

func (c *partiallyNopCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
return ce.AddCore(ent, c)
}

func (c *partiallyNopCore) With([]zapcore.Field) zapcore.Core { return c }
func (*partiallyNopCore) Write(zapcore.Entry, []zapcore.Field) error { return nil }
func (*partiallyNopCore) Sync() error { return nil }

0 comments on commit 48f2f4d

Please sign in to comment.