Golang學習筆記(7)測試與性能調優

第七章 測試與性能調優


測試

傳統測試 vs 表格驅動測試

傳統測試
  • 測試數據和測試邏輯混在一起
  • 出錯信息不明確
  • 一旦一個數據錯誤測試全部結束
表格驅動測試
  • 分離的測試數據和測試邏輯
  • 明確的出錯信息
  • 可以部分失敗
  • go語言的語法是的我們更容易實現表格驅動測試
func TestTriangle(t *testing.T) {
	tests := []struct{ a, b, c int }{
		{3, 4, 5},
		{5, 12, 13},
		{8, 15, 17},
		{12, 35, 37},
		{30000, 40000, 50000},
	}

	for _, tt := range tests {
		if actual := calcTriangle(tt.a, tt.b); actual != tt.c {
			t.Errorf("calcTriangle(%d, %d); "+
				"got %d; expected %d",
				tt.a, tt.b, actual, tt.c)
		}
	}
}
  • 命令行
go test ./
運行結果 :
ok      imooc.com/ccmouse/learngo/basic/basic   0.817s
代碼覆蓋率
  • goland裏 Run xxx With Coverage
  • 命令行
go test -coverprofile = c.out
// 輸出
PASS
coverage: 52.6% of statements
ok      imooc.com/ccmouse/learngo/container/nonrepeatingsubstr  0.953s
// 結果如下圖
go tool cover -html c.out

在這裏插入圖片描述

性能測試
func BenchmarkSubstr(b *testing.B) {
	s := "黑化肥揮發發灰會花飛灰化肥揮發發黑會飛花"
	ans := 8

	for i := 0; i < b.N; i++ {
		actual := lengthOfNonRepeatingSubStr(s)
		if actual != ans {
			b.Errorf("got %d for input %s; "+
				"expected %d",
				actual, s, ans)
		}
	}
}

// 輸出
2000000	       933 ns/op	// 200W次 每次執行耗時933納秒
PASS
  • 命令行
go test -bench ./
查看性能消耗
// 1.
go test -bench ./ -cpuprefile cpu.out
// 2.
go tool pprof cpu.out
// 3.進入pprof操作界面
Type: cpu
Time: Jun 5, 2019 at 10:25pm (CST)
Duration: 2.10s, Total samples = 2.13s (101.43%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)
// 4.web(需要安裝Graphviz)
// or text/top 輸出如下
Showing nodes accounting for 2.04s, 95.77% of 2.13s total
Dropped 19 nodes (cum <= 0.01s)
Showing top 10 nodes out of 30
      flat  flat%   sum%        cum   cum%
     0.53s 24.88% 24.88%      0.64s 30.05%  runtime.mapaccess2_fast32
     0.48s 22.54% 47.42%      0.61s 28.64%  runtime.mapassign_fast32
     0.41s 19.25% 66.67%      0.41s 19.25%  runtime.decoderune
     0.17s  7.98% 74.65%      0.58s 27.23%  runtime.stringtoslicerune
     0.12s  5.63% 80.28%      1.95s 91.55%  imooc.com/ccmouse/learngo/container/nonrepeatingsubstr.lengthOfNonRepeatingSubStr
     0.11s  5.16% 85.45%      0.11s  5.16%  runtime.add (inline)
     0.10s  4.69% 90.14%      0.10s  4.69%  runtime.aeshash32
     0.07s  3.29% 93.43%      0.07s  3.29%  runtime.procyield
     0.03s  1.41% 94.84%      0.03s  1.41%  runtime.bucketShift (inline)
     0.02s  0.94% 95.77%      0.02s  0.94%  runtime.stdcall1
文檔
  • 用註釋寫文檔
  • 在測試種加入Example
  • 使用go doc / godoc 來 查看/生成 文檔
  • 命令行
$ go doc Queue

Output:
type Queue []int
    A FIFO queue.
    
func (q *Queue) IsEmpty() bool
func (q *Queue) Pop() int
func (q *Queue) Push(v int)
$ go doc IsEmpty

func (q *Queue) IsEmpty() bool
    Returns if the queue is empty or not.
godoc -http : 6060
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章