Skip to content

Instantly share code, notes, and snippets.

@thiskevinwang
Created November 17, 2023 13:45
Show Gist options
  • Save thiskevinwang/17651f170f3e812b9c5b74040d4810a9 to your computer and use it in GitHub Desktop.
Save thiskevinwang/17651f170f3e812b9c5b74040d4810a9 to your computer and use it in GitHub Desktop.
go-bench
// benchmarking two flavors of logging
//
// run with `go test -benchmem -bench=.`
//
// Example output:
// ----------------------------------------------------------
// goos: darwin
// goarch: arm64
// pkg: go-benchmarks
// BenchmarkLogPlain-10 3548698 332.0 ns/op 64 B/op 2 allocs/op
// BenchmarkLogExtra-10 1528564 780.5 ns/op 376 B/op 6 allocs/op
// PASS
// ok go-benchmarks 3.603s
// ----------------------------------------------------------
package main
import (
"fmt"
"log"
"os"
"runtime"
"testing"
)
func logPlain(msg string) {
fmt.Println("some fairly long log message asldkasldkasjdl asda dadasdasdakasdlkasldkasldka", msg)
}
func logExtra(msg string) {
pc, _, _, _ := runtime.Caller(1)
fmt.Println(fmt.Sprintf("%s: some fairly long log message", runtime.FuncForPC(pc).Name()))
}
func BenchmarkLogPlain(b *testing.B) {
defer quiet()()
for i := 0; i < b.N; i++ {
logPlain("test")
}
}
func BenchmarkLogExtra(b *testing.B) {
defer quiet()()
for i := 0; i < b.N; i++ {
logExtra("test")
}
}
// https://stackoverflow.com/a/58720235/9823455
func quiet() func() {
null, _ := os.Open(os.DevNull)
sout := os.Stdout
serr := os.Stderr
os.Stdout = null
os.Stderr = null
log.SetOutput(null)
return func() {
defer null.Close()
os.Stdout = sout
os.Stderr = serr
log.SetOutput(os.Stderr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment