Skip to content

三十三、Benchmark

wenjianzhang edited this page Nov 13, 2019 · 1 revision

Benchmark

func BenchmarkConcatStringByAdd(b *testing.B) {
	//与性能测试无关代码
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// 测试代码
	}
	b.StopTimer()
	//与性能测试无关代码
}

示例代码

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()
	var buf bytes.Buffer
	for i := 0; i < b.N; i++ {
		for _, elem := range elems {
			buf.WriteString(elem)
		}
	}
	b.StopTimer()
}

Terminal中执行

$ go test -bench=. 
goos: darwin
goarch: amd64
pkg: github.com/wenjianzhang/golearning/src/ch33/benchmark
BenchmarkConcatStringByAdd-4            10000000               118 ns/op
BenchmarkConcatStringByBytesBuffer-4    50000000                35.1 ns/op
PASS
ok      github.com/wenjianzhang/golearning/src/ch33/benchmark   3.718s

go test -bench=. -benchmem

  • -bench=<相关benchmark测试>
  • Windows下使用go test 命令行时, -bench=. 应写成 -bench="."
─$ go test -bench=. -benchmem
goos: darwin
goarch: amd64
pkg: github.com/wenjianzhang/golearning/src/ch33/benchmark
BenchmarkConcatStringByAdd-4            10000000               140 ns/op              16 B/op       4 allocs/op
BenchmarkConcatStringByBytesBuffer-4    30000000                44.2 ns/op            18 B/op       0 allocs/op
PASS
ok      github.com/wenjianzhang/golearning/src/ch33/benchmark   3.062s
Clone this wiki locally