Skip to content

Instantly share code, notes, and snippets.

@peketamin
Last active July 24, 2020 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peketamin/a56d3b9179db5e6e75dbec9ec1905eec to your computer and use it in GitHub Desktop.
Save peketamin/a56d3b9179db5e6e75dbec9ec1905eec to your computer and use it in GitHub Desktop.
go benchmark test
package cat
import (
"bytes"
)
func buf(ss []string) string {
var b bytes.Buffer
for _, s := range ss {
b.WriteString(s)
}
return b.String()
}
package cat
import (
"strings"
"testing"
)
func seed(n int) []string {
s := make([]string, 0, n)
for i := 0; i < n; i++ {
s = append(s, "a")
}
return s
}
func BenchmarkBuf(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
buf(seed(i * 10))
}
}
func BenchmarkJoin(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
strings.Join(seed(i*10), "")
}
}
% go vet ./...
% go test -bench ./...
?   	_/Users/peketamin/ghq/github.com/peketamin/big-stones	[no test files]

% go test ./... -bench .+
goos: darwin
goarch: amd64
BenchmarkHello-8   	24976813	        44.3 ns/op
PASS
ok  	_/Users/peketamin/ghq/github.com/peketamin/big-stones	1.212s
goos: darwin
goarch: amd64
BenchmarkBuf-8    	   10000	    645318 ns/op
BenchmarkJoin-8   	   10000	    716953 ns/op
PASS
ok  	_/Users/peketamin/ghq/github.com/peketamin/big-stones/cat	13.682s
% tree .
.
├── README.md
├── cat
│   ├── cat.go
│   └── cat_test.go
├── chan
├── chan.go
└── chan_test.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment