访问基准测试结果

3
我看到Go语言中有一个名为testing.BenchmarkResult的结构体,可以用来访问基准测试结果,但是我发现很少有文档或示例可以帮助我使用它。

目前,我只能像这样对我的函数进行基准测试:

func BenchmarkMyFunction(b *testing.B) {
   // call to myFunction
}

然后运行:

go test -bench=".*"

这里的结果被打印到控制台,但我想将它们存储在一个单独的文件中。我该如何使用BenchmarkResult类型来实现这一点?


2
只需在您的shell中将stdout重定向到一个文件即可。 - undefined
请注意,基准测试需要查看b.N才能发挥作用。请参阅https://golang.org/pkg/testing/#hdr-Benchmarks。 - undefined
另外,正如文档中推荐的那样,你可以使用go test -bench=.来运行所有的基准测试。这样就避免了在shell中转义/引用*的需要。 - undefined
还有一个go test命令的-json标志(添加于Go 1.10)可以将测试结果以可机器解析的JSON格式输出。 - undefined
1个回答

5

例如:

package main

import (
    "fmt"
    "testing"
    "time"
)

func Add(a, b int) int {
    time.Sleep(10 * time.Microsecond) // Just to make the test take some time
    return a + b
}

func BenchAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = Add(1, 2)
    }
}

func main() {
    res := testing.Benchmark(BenchAdd)
    fmt.Printf("%s\n%#[1]v\n", res)
}

生成:

  120000         10000 ns/op
testing.BenchmarkResult{N:120000, T:1200000000, Bytes:0, MemAllocs:0x0, MemBytes:0x0, Extra:map[string]float64{}}

Playground

您可以使用ioutil.WriteFile轻松将这些结果写入文件中。 带有WriteFile的Playground


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接