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

Golang学习笔记(7)测试与性能调优_第1张图片

性能测试
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

你可能感兴趣的:(Go学习笔记)