标签:ash chm mat time demo 使用 一个 package 测试
testing
"github.com/stretchr/testify/assert"
func TestDemo(t *testing.T) {
assert.Nil(t, nil)
assert.NotNil(t, struct{}{})
assert.Equal(t, 5, 5)
assert.NotEqual(t, 5, 6)
}
执行 go test <filename> -v
-v 参数是查看详细结果
基准测试(Benchmark)应该注意避免在虚拟机以及云服务器上测试。虚拟机、云服务器上资源动态分配可能会导致测试结果有误。
BenchmarkFoo(b *testing.B)
go test -bench=".*" -benchmem
执行
下面看一个列子,观察两种不同方式初始化 slice 对性能的影响。
make([]int, 0, 100)
表示初始化长度为 0,容量为 100 的 slicemake(map[string]int, 10)
表示容量为 10make(chan int, 10)
表示容量为 10package test
import (
"math/rand"
"testing"
"time"
)
func FillingSlice(n int) []int {
rand.Seed(time.Now().UnixNano())
list := make([]int, 0)
for i := 0; i < n; i++ {
list = append(list, rand.Int())
}
return list
}
func FillingSliceWithCap(n int) []int {
rand.Seed(time.Now().UnixNano())
// make ==> type, len, cap
list := make([]int, 0, n)
for i := 0; i < n; i++ {
list = append(list, rand.Int())
}
return list
}
// Benchmark Test
func BenchmarkFillingSlice(b *testing.B) {
for k := 0; k < b.N; k++ {
FillingSlice(10000000)
}
}
func BenchmarkFillingSliceWithCap(b *testing.B) {
for k := 0; k < b.N; k++ {
FillingSliceWithCap(10000000)
}
}
执行 go test -bench=".*" -benchmem -count=6 .
goos: linux
goarch: amd64
pkg: tdmq.learn/test
BenchmarkFillingSlice-2 4 262980589 ns/op 423503132 B/op 50 allocs/op
BenchmarkFillingSlice-2 4 254879772 ns/op 423503132 B/op 50 allocs/op
BenchmarkFillingSlice-2 4 252118532 ns/op 423503132 B/op 50 allocs/op
BenchmarkFillingSlice-2 4 257549132 ns/op 423503110 B/op 50 allocs/op
BenchmarkFillingSlice-2 4 261797872 ns/op 423503104 B/op 50 allocs/op
BenchmarkFillingSlice-2 4 255670030 ns/op 423503106 B/op 50 allocs/op
BenchmarkFillingSliceWithCap-2 7 153076230 ns/op 80003072 B/op 1 allocs/op
BenchmarkFillingSliceWithCap-2 7 153764944 ns/op 80003072 B/op 1 allocs/op
BenchmarkFillingSliceWithCap-2 7 155534140 ns/op 80003072 B/op 1 allocs/op
BenchmarkFillingSliceWithCap-2 7 154345444 ns/op 80003072 B/op 1 allocs/op
BenchmarkFillingSliceWithCap-2 7 152601362 ns/op 80003072 B/op 1 allocs/op
BenchmarkFillingSliceWithCap-2 7 154338301 ns/op 80003072 B/op 1 allocs/op
标签:ash chm mat time demo 使用 一个 package 测试
原文地址:https://www.cnblogs.com/owenqing/p/14396534.html