這裡分類和彙總了欣宸的全部原創(含配套原始碼):https://github.com/zq2599/blog_demos
-《Go語言基準測試(benchmark)三部曲》已近尾聲,經歷了《基礎篇》和《記憶體篇》的實戰演練,相信您已熟練掌握了基準測試的常規操作以及各種引數的用法,現在可以學習一些進階版的技能了,在面對複雜一些的場景也能高效完成基準測試,另外還有幾個坑也要提前瞭解,避免以後掉進去
func BenchmarkFib(b *testing.B) {
for n := 0; n < b.N; n++ {
fib(30)
}
}
// BenchmarkFibWithPrepare 進入正式測試前需要耗時做準備工作的case
func BenchmarkFibWithPrepare(b *testing.B) {
// 假設這裡有個耗時800毫秒的初始化操作
<-time.After(800 * time.Millisecond)
// 這下面才是咱們真正想做基準測試的程式碼
for n := 0; n < b.N; n++ {
fib(30)
}
}
go test -bench='BenchmarkFib|BenchmarkFibWithPrepare' benchmark-demo
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkFib-8 325 3637442 ns/op
BenchmarkFibWithPrepare-8 50 20173566 ns/op
PASS
ok benchmark-demo 14.871s
go test -bench='BenchmarkFib|BenchmarkFibWithPrepare' benchmark-demo
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkFib-8 325 3616239 ns/op
BenchmarkFibWithPrepare-8 316 3729323 ns/op
PASS
ok benchmark-demo 5.628s
func BenchmarkFibWithClean(b *testing.B) {
// 這下面才是咱們真正想做基準測試的程式碼
for n := 0; n < b.N; n++ {
fib(30)
// 假設這裡有個耗時100毫秒的清理操作
<-time.After(10 * time.Millisecond)
}
}
go test -bench='BenchmarkFib$|BenchmarkFibWithClean' benchmark-demo
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkFib-8 322 3610100 ns/op
BenchmarkFibWithClean-8 81 16139196 ns/op
PASS
ok benchmark-demo 3.002s
// BenchmarkFibWithClean 假設每次執行完fib方法後,都要做一次清理操作
func BenchmarkFibWithClean(b *testing.B) {
// 這下面才是咱們真正想做基準測試的程式碼
for n := 0; n < b.N; n++ {
// 繼續記錄耗時
b.StartTimer()
fib(30)
// 停止記錄耗時
b.StopTimer()
// 假設這裡有個耗時100毫秒的清理操作
<-time.After(10 * time.Millisecond)
}
}
go test -bench='BenchmarkFib$|BenchmarkFibWithClean' benchmark-demo
goos: darwin
goarch: arm64
pkg: benchmark-demo
BenchmarkFib-8 325 3631020 ns/op
BenchmarkFibWithClean-8 241 7448678 ns/op
PASS
ok benchmark-demo 7.751s
// BenchmarkFibWrongA 演示了錯誤的基準測試程式碼,這樣的測試可能無法結束
func BenchmarkFibWrongA(b *testing.B) {
for n := 0; n < b.N; n++ {
fib(n)
}
}
func BenchmarkFibWrongB(b *testing.B) {
fib(b.N)
}