go 基准测试

2018-11-27  本文已影响0人  bocsoft

在 Go 中编写[基准测试] 是该语言的另一个一级特性,它与编写测试非常相似

func BenchmarkRepeat(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Repeat("a")
    }
}

你会看到上面的代码和写测试差不多。

testing.B 可使你访问隐性命名(cryptically named)b.N。

基准测试运行时,代码会运行 b.N 次,并测量需要多长时间。

代码运行的次数应该不影响你,框架将决定什么是「好」的值,以便让你获得一些得体的结果。

用 go test -bench=. 来运行基准测试。

注意:基准测试默认是顺序运行的

package iteration

const repeatCount = 5

func Repeat(character string) string {
    var repeated string
    for i := 0; i < repeatCount; i++ {
        repeated += character
    }
    return repeated
}



package iteration

import "testing"

func TestRepeat(t *testing.T) {
    repeated := Repeat("a")
    expected := "aaaaa"

    if repeated != expected {
        t.Errorf("expected '%s' but got '%s'", expected, repeated)
    }
}

func BenchmarkRepeat(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Repeat("a")
    }
}

输出结果如下:
goos: windows
goarch: amd64
pkg: gopcp/learn-go-with-tests/iteration/vx
BenchmarkRepeat-4        5000000           244 ns/op
PASS

上一篇 下一篇

猜你喜欢

热点阅读