性能优化测试| 青训营

74 阅读1分钟

性能优化

预分配内存

data := make([]int,0)
 
data := make([]int,0,10)   // 相比第一个预分配了10的内存

拼接字符串

import bytes

var buf bytes.Buffer
buf.WriteString("aaa")
buf.WriteString("bbb")
buf.String()   // 返回 "aaabbb"

测试

单元测试

  • 分别测试各个模块

运行命令

cover测试代码的覆盖率(运行了的代码在测试代码中的占比)

相关测试函数左边点击运行

指定测试文件和被测试文件
go test hello_test.go hello.go --cover  

go test -cover   

测试规则

  • 所有测试文件都是以_test.go 结尾
程序文件hello.go
// test/hello.go
package test

func HelloWorld(a int) string{
	if a == 1 {
		return "hello world"
	} else {
		return "error"
	}
}
测试文件hello_test.go
package test

import "testing"

// 测试函数命名都是以Test开头 Test后面的首字母也需要大写
func TestHelloWorld(t *test.T){
	isPass := HelloWorld(1)

	// 格式化打印error 并且结束测试
	t.Errorf("%v", isPass)

	// 打印日志
	t.Log()
}

// 初始化逻辑放在TestMain中
func TestMain(m *test.M){
	code
}

测试结果

        test    coverage: 66.7% of statements
ok      test    0.571s

基准测试

  • 在负载下检测程序性能的测试方法

执行命令

相关测试函数左边点击运行

test -benchmem -run=^$ -bench ^BenchmarkAdd2$ test

测试规则

  • 程序文件同上

测试文件hello_test.go

func BenchmarkAdd2(b *testing.B) {
	// 通过循环测试负载性能
    for i := 0; i < b.N; i++ {
        add(4)
    }
}

测试结果

  • ns/op 为平均每次执行的秒数
  • B/op 为平均每次
1000000000               0.4238 ns/op          0 B/op          0 allocs/op
PASS
ok      test    1.437s