主页

索引

模块索引

搜索页面

1.5.2. Benchmarks

func BenchmarkXxx(*testing.B)

实例:

func BenchmarkHello(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fmt.Sprintf("hello")
    }
}

If a benchmark needs some expensive setup before running, the timer may be reset:

func BenchmarkBigLen(b *testing.B) {
    big := NewBig()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        big.Len()
    }
}

If a benchmark needs to test performance in a parallel setting:

func BenchmarkTemplateParallel(b *testing.B) {
    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    b.RunParallel(func(pb *testing.PB) {
        var buf bytes.Buffer
        for pb.Next() {
            buf.Reset()
            templ.Execute(&buf, "World")
        }
    })
}

运行:

$ go test -bench=. -run=none

// 测试时间默认是1秒,如果想让测试运行的时间更长,可以通过-benchtime指定,比如3秒
$ go test -bench=. -benchtime=3s -run=none

// -benchmem可以提供每次操作分配内存的次数,以及每次操作分配的字节数
go test -bench=. -benchmem -run=none

性能测试实例:

 1package gotest
 2
 3import (
 4    "testing"
 5)
 6
 7func Benchmark_Division(b *testing.B) {
 8    for i := 0; i < b.N; i++ { //use b.N for looping 
 9        Division(4, 5)
10    }
11}
12
13func Benchmark_TimeConsumingFunction(b *testing.B) {
14    b.StopTimer() //调用该函数停止压力测试的时间计数
15
16    //做一些初始化的工作,例如读取文件数据,数据库连接之类的,
17    //这样这些时间不影响我们测试函数本身的性能
18
19    b.StartTimer() //重新开始时间
20    for i := 0; i < b.N; i++ {
21        Division(4, 5)
22    }
23}

主页

索引

模块索引

搜索页面