Go之Benchmark
一、概念
基準測試(benchmark)是 go testing 庫提供的,用來度量程序性能,算法優劣的利器。
指定一個時間(默認是1秒),看測試對象在達到時間上限時,最多能被執行多少次和在此期間測試對象內存分配情況。
?
二、特點
?
三、常用API
?
四、操作的命令
go test -bench=BenchmarkFoo
go test -bench=.
// 加上 -bench= 測試名字, .表示運行所有的基準測試,名字可用正則。
go test -bench=BenchmarkFoo -benchtime=5s/10000x
// 加上 -benchtime 設置時間,s表示秒,x表示執行次數
go test -bench=BenchmarkFoo -benchtime=5s -count=3
// 加上 -count 表示幾次測試
go test -bench=. -benchmem
// 加上 -benchmem 查看內存
go test -bench=. -benchmem -cpuprofile profile.out
go test -bench=. -benchmem -memprofile memprofile.out
go tool pprof profile.out
go tool pprof memprofile.out
// 結合 pprof 輸出查看 cpu和內存。
?
五、使用的方式
串行
func BenchmarkFoo(b *testing.B) {for i:=0; i<b.N; i++ {dosomething()} }并行
func BenchmarkFoo(b *testing.B) {b.RunParallel(func(pb *testing.PB) {for pb.Next() {dosomething()}}) }并行的goroutine個數是默認等于runtime.GOMAXPROCS(0)。
釋義:創建P個goroutine之后,再把b.N打散到每個goroutine上執行
增大goroutine的個數,使用 b.SetParallelism(p int)
func BenchmarkFoo(b *testing.B) { b.SetParallelism(10)b.RunParallel(func(pb *testing.PB) {for pb.Next() {dosomething()}}) }// 原理: 最終goroutine個數 = 形參p的值 * runtime.GOMAXPROCS(0)
numProcs := b.parallelism * runtime.GOMAXPROCS(0)
?
StartTimer()、StopTimer()、ResetTimer()
init(); // 初始化工作 b.ResetTimer() for i:=0; i<b.N; i++ { dosomething1() } b.StopTimer()otherWork(); // 例如做一些轉換工作 b.StartTimer() for i:=0; i<b.N; i++ { dosomething2() }方式二
init(); // 初始化工作 b.ResetTimer() for i:=0; i<b.N; i++ {flag := dosomething()if flag {b.StopTimer()} else {b.StartTimer()} }StartTimer()、ResetTimer() 都是記錄當前時間為開始時間 和 內存分配情況,不過 ResetTimer()多了清空重置操作。
StopTimer() 累計記錄執行的時間(當前時間 - 記錄的開始時間),累計記錄內存分配次數和分配字節數
Run()
表驅動法
func BenchmarkRR(b *testing.B) {tests := []struct {keyLength int}{{keyLength: 16},{keyLength: 32},}for _, t := range tests {name := fmt.Sprintf("%vKeyLength", t.keyLength)b.Run(name, func(b *testing.B) {dosomething(b, t.keyLength)})} }?
六、例子
fib.go
// 斐波那契數列 func fib(n int) int {if n < 2 {return n}return fib(n-1) + fib(n-2) } func sum(a, b int) int {return a + b }?
fib_test.go
import "testing" func BenchmarkFib10(b *testing.B) {for n := 0; n < b.N; n++ {fib(10)} } func BenchmarkFib20(b *testing.B) {for n := 0; n < b.N; n++ {fib(20)} } func BenchmarkSum(b *testing.B) {for n := 0; n < b.N; n++ {sum(1, 2)} }?
使用正則
使用-benchting
使用-benchting 的x單位
使用-count
?
?
總結
以上是生活随笔為你收集整理的Go之Benchmark的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Benchmark 第一篇 了解Benc
- 下一篇: Ruby使用RabbitMQ(基础)