6

Golang | 测试与性能调优 - 一点浩然气~

 2 years ago
source link: https://www.cnblogs.com/FrostBoy/p/16104697.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Golang | 测试与性能调优

我们在日常的工作过程中,自测是不可缺少的,公司还会要求所有的公共方法必须要写单测,在别的语言中,我们如果想要写单测还需要使用到测试框架,但是Go语言中,直接支持测试,并且使用起来非常简单。

比如说我现在写了一个:

// twoSum 给定数组,求两个之和的数组内地址
func twoSum(nums []int, target int) []int {
	hashTable := map[int]int{}
	for i, x := range nums {
		if p, ok := hashTable[target-x]; ok {
			return []int{p, i}
		}
		hashTable[x] = i
	}
	return nil
}

这个方法是求两数之和的,这个方法是公共方法,现在我需要对这个方法进行单测,我们只需要在同一目录下新建一个以 _test结尾的文件就可以了。

package twoSum

import (
	"testing"
)

func TestTwoSum(t *testing.T) {
	
}

新建一个函数,以Test开头,以刚刚的方法名结尾,参数默认是 testing包中的。

现在我们就可以写测试内容了:

func TestTwoSum(t *testing.T) {
	args := []struct {
		nums   []int
		target int
		source []int
	}{
		{[]int{2, 7, 11, 15}, 9, []int{0, 1}},
		{[]int{2, 7, 11, 15}, 13, []int{0, 2}},
		{[]int{0, 1, 0}, 0, []int{0, 2}},
	}
	for _, arg := range args {
		sum := twoSum(arg.nums, arg.target)
		for i, v := range sum {
			if arg.source[i] != v {
				fmt.Printf("nums:%v,target:%v,right:%v,source:%v", arg.nums, arg.target, sum, arg.source)
			}
		}
	}
}

以上就是测试方法的内容了,这和我们平时写的测试不太一样,是因为这是表格驱动测试。

把输入和输出放到同一个结构体内,然后循环去执行测试,把测试不通过的测试案例输出出来,并且符上正确答案,这种方法更加的直观一点,也更加的方便,在Go语言中我们使用这种方法测试更加的简单一点,别的语言如果使用这测试方法可能全非常的麻烦。

测试代码覆盖率

image-20220405181624209

使用命令go test -coverprofile=c.out 成生代码覆盖率文件。

然后通过 go tool cover -html=c.out查看文件内容:

image-20220405181743686

一般我们写完测试代码之后,这个函数的测试工作就算完成了,但是有时当一个函数特别重要时,我还还需要对这个函数进行性能测试,Go语言也对性能测试提供了支持:

func BenchmarkTwoSum(b *testing.B) {
	nums := []int{2, 7, 11, 15, 24, 22, 44}
	target := 9
	source := []int{0, 1}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		sum := twoSum(nums, target)
		for i, v := range sum {
			if source[i] != v {
				fmt.Printf("nums:%v,target:%v,right:%v,source:%v", nums, target, sum, source)
			}
		}
	}
}

函数名以Benchmark开头,以要测试的函数名结尾。函数体为测试内容。

b.ResetTimer() // 数据准备完成,从这一行对性能进行统计
b.N		// 循环的次数由系统决定

使用命令对函数进行测试:

go test -bench .

image-20220405182243005

以上就是测试内容,一共运行了:31572230 次,每次用时 34.93 ns

当然,有时我们想知道这个函数的性能瓶颈在那我们也可以通过命令来实现:

image-20220405182819411

# 通过命令生成性能测试文件
go test -bench . -cpuprofile cpu.out
# 能过web方式查看性能文件
go tool pprof cpu.out
# 最后输入 web 后会自动弹出网页
web

image-20220405183224556

通过网页我们可以更直观的看到性能瓶颈在那。

如果想要查看性能文件必须提前安装:graphviz

关注公众号,随时获取最新资讯

细节决定成败!
个人愚见,如有不对,恳请斧正!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK