本节主要记录golang测试代码、查看代码性能、优化代码的相关操作编写工具用的是vscode
下面是此次测试的代码:
package main_test
import (
"testing"
)
func BenchmarkTest(b *testing.B) {
str := "dewfewfewgthre"
n := 7
for i := 0; i < b.N; i++ {
if actual := lengthOfNoRepeatingSubStr(str); actual != n {
b.Errorf("got %d for input %s; expected %d", actual, str, n)
}
}
}
//求最大不重复子字符串的长度
func lengthOfNoRepeatingSubStr(str string) int{
lastOccurred := make(map[rune]int)
start := 0
maxLength := 0
for i, ch := range []rune(str){
if lastI, ok := lastOccurred[ch]; ok && lastI >= start{
start = lastI + 1
}
if i - start + 1 > maxLength{
maxLength = i - start + 1
}
lastOccurred[ch] = i
}
return maxLength
}
具体步骤如下:
1、创建一个新目录,新建go代码脚本,脚本名需要带test,如:profiler_test.go;
2、写一个测试的函数;
3、新建以Benchmark开头的函数,在新建的函数里调用测试的函数,调用次数是由testing.B里的N字段控制,即上述代码中的循环次数:b.N;b.ResetTimer()可以重置计时器;
4、开始调试,在terminal终端进行调试:
①、输入go test -bench .
可查看循环调用了测试代码的次数以及每次调用测试代码耗费的时间。
运行结果如下:
E:\Go\src\TestProfilerProject>go test -bench .
goos: windows
goarch: amd64
pkg: TestProfilerProject
BenchmarkTest-4 3000000 413 ns/op
PASS
ok TestProfilerProject 1.805s
②、输入go test -bench . -cpuprofile cpu.out
可以把运行代码过程的各种信息输出到cpu.out文件中,生成的cpu.out跟代码目录同级
运行结果如下:
E:\Go\src\TestProfilerProject>go test -bench . -cpuprofile cpu.out
goos: windows
goarch: amd64
pkg: TestProfilerProject
BenchmarkTest-4 3000000 421 ns/op
PASS
ok TestProfilerProject 2.214s
③、输入go tool pprof cpu.out
由于第②步生成的cpu.out是一个二进制文件,我们无法直接查看其信息,所以要执行这一步的命令,这个命令执行后提供一个交互式接口,我们可以输入指定的命令来完成相关的操作
运行结果如下:
E:\Go\src\TestProfilerProject>go tool pprof cpu.out
Type: cpu
Time: Jul 31, 2019 at 4:37pm (CST)
Duration: 1.90s, Total samples = 1.71s (89.93%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)
执行后输出末尾会进入等待输入状态,为了查看cpu.out的具体内容,我们需要借助Graphviz 软件让这些信息可视化。
Graphviz 的安装可参考:https://www.cnblogs.com/shuodehaoa/p/8667045.html
④、输入dot
得到dot代码,把这些代码复制到Graphviz软件中即可生成我们的测试代码运行信息图,代码哪些地方消耗性能较多、占用的时间较多都一目了然。