golang-测试

一、代码覆盖率和性能测试

1、代码覆盖率

代码

# 将代码覆盖率报告输出到c.out文件中
$ go test -coverprofile=c.out
# 查看代码覆盖率
$ go tool cover -html=c.out

效果

// 测试方法对这段代码的代码覆盖率
func twoSum(nums []int, target int) []int {
	m := make(map[int]int)
	for i, num := range nums {
		if val, ok := m[target-num]; ok {
			return []int{val, i}
		}
		m[num] = i
	}
	return nil
}

在这里插入图片描述

2、性能测试

// 需要以 Benchmark 开头
func BenchmarkTwoSum(b *testing.B) {
	var (
		nums = []int{2, 7, 11, 15}
		target = 9
		want = []int{0, 1}
	)
	
	// b.N 代表代码测试的次数
	for i := 0; i < b.N; i++ {
		if got := twoSum(nums, target); !reflect.DeepEqual(got, want) {
			b.Errorf("twoSum() = %v, want %v", got, want)
		}
	}
}

效果

$ go test -bench .
goos: windows
goarch: amd64
pkg: pyc/leetcode/_0_50
BenchmarkTwoSum-16       2660191               451 ns/op
PASS
ok      pyc/leetcode/_0_50      1.953s

分析
可以通过结果看到,总共测试了2660191次,每次执行方法耗时451 ns

3、通过pprof进行性能调优

# 生成性能报告文件 cup.out
$ go test -bench . -cpuprofile cpu.out
# 使用pprof分析报告
$ go tool pprof cpu.out
Type: cpu
Time: Sep 5, 2021 at 9:44am (CST)
Duration: 1.83s, Total samples = 2.07s (113.03%)
Entering interactive mode (type "help" for commands, "o" for options)
# 查看可视化视图
(pprof) web

注意:需要提前按照 graphviz
安装地址: http://graphviz.org/download/

效果: 通过图片分析代码慢在哪
在这里插入图片描述

二、生成文档和示例代码

1、生成文档

# 获取godoc
$ go get golang.org/x/tools/cmd/godoc
# 查看生成的文档
$ godoc -http :6060

效果
在这里插入图片描述

2、示例代码

// 必须以Example开头
func ExampleTwoSum() {
	var (
		nums = []int{2, 7, 11, 15}
		target = 9
	)
	want := TwoSum(nums, target)
	fmt.Println(want)

	// Output:
	// [0 1]
}
$ godoc -http :6060

效果
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值