【Duke】BenchMark 034 - PingPongGooo/GoFoundation GitHub Wiki
Benchmark 代码性能的测评
func BenchmarkConcatStringByAdd(b *testing.B){
// 与性能测试无关的代码
b.ResetTimer()
for i:=0; i<b.N; i++{
// 测试代码
}
b.StopTimer()
// 与性能测试无关的代码
}
package benchmark
import (
"bytes"
assert2 "github.com/stretchr/testify/assert"
"testing"
)
func TestConcatStringByAdd(t *testing.T){
assert:=assert2.New(t)
elems:=[]string{"1","2","3","4","5"}
ret := ""
for _,elem := range elems{
ret += elem
}
assert.Equal("12345",ret)
}
func TestConcatStringByBytesBuffer(t *testing.T) {
assert := assert2.New(t)
var buf bytes.Buffer
elems := []string{"1","2","3","4","5"}
for _,elem := range elems{
buf.WriteString(elem)
}
assert.Equal("12345",buf.String())
}
func BenchmarkConcatStringByAdd(b *testing.B){
elems:=[]string{"1","2","3","4","5"}
b.ResetTimer()
for i := 0; i<b.N;i++ {
ret := ""
for _,elem := range elems{
ret += elem
}
}
b.StopTimer()
}
func BenchmarkConcatStringByBytesBuffer(b *testing.B) {
elems := []string{"1","2","3","4","5"}
b.ResetTimer()
for i := 0; i<b.N;i++ {
var buf bytes.Buffer
for _,elem := range elems{
buf.WriteString(elem)
}
}
b.StopTimer()
}
D:\Develop\GoWork\src\GoFoundation\go_learn\ch35\benchmark>go test -bench=.
goos: windows
goarch: amd64
pkg: GoFoundation/go_learn/ch35/benchmark
BenchmarkConcatStringByAdd-8 7162570 182 ns/op
BenchmarkConcatStringByBytesBuffer-8 13437127 84.0 ns/op
PASS
ok GoFoundation/go_learn/ch35/benchmark 3.297s
D:\Develop\GoWork\src\GoFoundation\go_learn\ch35\benchmark>go test -bench=. -benchmem
goos: windows
goarch: amd64
pkg: GoFoundation/go_learn/ch35/benchmark
BenchmarkConcatStringByAdd-8 6537823 191 ns/op 16 B/op 4 allocs/op
BenchmarkConcatStringByBytesBuffer-8 14407370 86.0 ns/op 64 B/op 1 allocs/op
PASS
ok GoFoundation/go_learn/ch35/benchmark 3.243s
Benchmark
go test -bench=. -benchmem
-bench=<相关benchmark测试>
Windows下使用go test命令行时, -bench=.应写为 -bench="."