测试与性能调优 | 青训营笔记

98 阅读2分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第2篇笔记

测试

1.分类

2.规则:

3.代码覆盖率

 go test ...   --cover

4.Mock

bouk/monkey: Monkey patching in Go (github.com)

go get bou.ke/monkey

package mock

import (
	"reflect"
	"strings"
	"testing"

	"bou.ke/monkey"
)

func TestUser_GetInfo(t *testing.T) {
	var u = &User{
		Name:     "q1mi",
		Birthday: "1990-12-20",
	}

	// 为对象方法打桩
	monkey.PatchInstanceMethod(reflect.TypeOf(u), "CalcAge", func(*User) int {
		return 18
	})

	ret := u.GetInfo() // 内部调用u.CalcAge方法时会返回18
	if !strings.Contains(ret, "朋友") {
		t.Fatal()
	}
}

5.基准测试


rand ---> fastrand

//牺牲了随机数的一致性

性能调优

1.pprof功能

2.实战排查

github.com/wolfogre/go…

2.1浏览器查看:

http://localhost:8080/debug/pprof/

2.2 CPU


# 采样10s
go tool pprof "http://localhost:8080/debug/pprof/profile?seconds=10"

# 查看占用资源最多的函数 
top

# 根据指定的正则表达式查找代码行
list

# 可视化工具
web

Flat ==Cum, 函数中没有调用其他函数

Flat==0, 函数中只有其他函数的调用

2.3 Heap堆内存

# 1.分析Heap:
go tool pprof --http=:8080 "http://localhost:8080/debug/pprof/heap"
# 2.打开web页面
go tool pprof --http=:8080 ./A文件,      然后浏览器会直接打开localhost:8080访问


# 查看内存占用数据
go tool pprof -inuse_space http://127.0.0.1:8080/debug/pprof/heap
go tool pprof -inuse_objects http://127.0.0.1:8080/debug/pprof/heap
# 查看临时内存分配数据
go tool pprof -alloc_space http://127.0.0.1:8080/debug/pprof/heap
go tool pprof -alloc_objects http://127.0.0.1:8080/debug/pprof/heap

Windows安装Graphiviz:

Download | Graphviz

2.4goroutine 协程

go tool pprof --http=:8081 "http://localhost:8080/debug/pprof/goroutine"

2.5锁

go tool pprof --http=:8081 "http://localhost:8080/debug/pprof/mutex"

2.6阻塞

go tool pprof --http=:8081 "http://localhost:8080/debug/pprof/block"

3.采样原理和过程

4.调优对象:

  • 业务服务优化
  • 基础库优化
  • Go 语言优化

5.性能优化与软件质量

  • 软件质量至关重要
  • 在保证接口稳定的前提下改进具体实现
  • 测试用例:覆盖尽可能多的场景,方便回归
  • 文档:做了什么,没做什么,能达到怎样的效果
  • 隔离:通过选项控制是否开启优化
  • 可观测:必要的日志输出