[原]壓力測試
版權宣告:本文為博主尹成聯絡QQ77025077,微信18510341407原創文章,歡迎轉載侵權不究。https://blog.csdn.net/yincheng01/article/details/84136139
壓力測試概述
壓力測試用來檢測函式(方法)的效能,和編寫單元功能測試的方法類似,但需要注意以下幾點:
- 檔名命名規則:xxx_test.go
- 函式名命名規則:func BenchXxx(b *testing.B),其中XXX可以是任意字母數字的組合,但是首字母不能是小寫字母
- 函式內必須使用b.N進行輪詢測試
- 函式內可以選擇使用b.ReportAllocs()彙報記憶體開銷
- 在GoLandIDE中你可以在待測包上右鍵,Run->gobentch xxx,以執行整包的壓力測試,預設從上向下依次執行所有
- 終端執行當前包下的所有壓力測試:
go test -bench=.
- 終端執行多次求平均值
go test -bench=. -count=3
定義待測的工具函式
這裡給出了斐波那契數列的遞迴和非遞迴兩種演算法實現
//獲取斐波那契數列第n項的遞迴實現 //1,1,2,3,5,8,13,21,34,55 func GetFibonacci1(n int) int { if n == 0 || n == 1 { return 1 } else { return GetFibonacci1(n-1) + GetFibonacci1(n-2) } } //獲取斐波那契數列第n項的非遞迴實現 //1,1,2,3,5,8,13,21,34,55 func GetFibonacci2(n int) int { x, y := 1, 1 for i := 0; i < n; i++ { x, y = y, x+y } return x }
定義測試用例
//匯入測試工具包 import "testing" //測試用例1:多次測試函式GetFibonacci1,獲得平均執行時間 func BenchmarkGetFibonacci1(b *testing.B) { b.Log("BenchmarkGetFibonacci1") //彙報記憶體開銷 b.ReportAllocs() for i := 0; i < b.N; i++ { GetFibonacci1(10) } } //測試用例2:多次測試函式GetFibonacci2,獲得平均執行時間 func BenchmarkGetFibonacci2(b *testing.B) { b.Log("BenchmarkGetFibonacci2") //彙報記憶體開銷 b.ReportAllocs() for i := 0; i < b.N; i++ { GetFibonacci2(10) } }
執行結果
不難看出,演算法2的執行效率6.55納秒/次要遠遠優於演算法1的503納秒/次
定義待測試的結構體
//匯入包 import ( "encoding/json" "os" "fmt" ) //定義待測的結構體 type Student struct { Name string Ageint } //將當前物件存入JSON檔案 func (s *Student) Save() error { dstFile, _ := os.OpenFile("d:/temp/student.json", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) defer dstFile.Close() //fmt.Println("Save:s=",s) encoder := json.NewEncoder(dstFile) err := encoder.Encode(s) if err != nil { fmt.Println("儲存失敗,err=", err) return err } //fmt.Println("儲存成功!") return nil } //讀取JSON檔案,轉化為一個student物件,載入的結果存入s中 func (s *Student) Load() error { srcFile, _ := os.OpenFile("d:/temp/student.json", os.O_RDONLY, 0666) defer srcFile.Close() decoder := json.NewDecoder(srcFile) err := decoder.Decode(s) if err != nil { fmt.Println("載入失敗,err=", err) return err } //fmt.Println("載入成功!") return nil }
定義結構體函式的效能測試用例
//匯入測試工具包 import "testing" //測試用例1:多次測試學生的儲存方法,獲得平均執行時間 func BenchmarkStudentSave(b *testing.B) { b.Log("BenchmarkStudentSave") //彙報記憶體開銷 b.ReportAllocs() for i := 0; i < b.N; i++ { student := &Student{"張全蛋", 20} student.Save() } } //測試用例2:多次測試學生的載入方法,獲得平均執行時間 func BenchmarkStudentLoad(b *testing.B) { b.Log("BenchmarkStudentLoad") //彙報記憶體開銷 b.ReportAllocs() for i := 0; i < b.N; i++ { student := &Student{} student.Load() } }
執行效果
學院Go語言視訊主頁
ofollow,noindex" target="_blank">https://edu.csdn.net/lecturer/1928