访问基准测试结果

huangapple go评论98阅读模式
英文:

Accessing a benchmark's result

问题

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

到目前为止,我只是这样对我的函数进行基准测试:

  1. func BenchmarkMyFunction(b *testing.B) {
  2. // 调用我的函数
  3. }

然后运行:

  1. go test -bench=".*"

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

英文:

I've seen there is a struct testing.BenchmarkResult in Go to accesss the result of a benchmark but I found very little documentation or examples to help me use it.

<!-- original had this link:
http://golang.org/src/testing/benchmark.go?s=5790:6120#L212
Bit that type of link is fragile (the higlighted bytes change whenever Go changes that source file) and not even clear what the OP was attempting to highlight. -->

So far I have only been benchmarking my functions like this:

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

And then running:

  1. go test -bench=&quot;.*&quot;

Here the results are printed to the console but I'd like to store them in a separate file. How can I use the BenchmarkResult type to do this?

答案1

得分: 4

例如:

  1. package main
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. )
  7. func Add(a, b int) int {
  8. time.Sleep(10 * time.Microsecond) // 只是为了让测试花费一些时间
  9. return a + b
  10. }
  11. func BenchAdd(b *testing.B) {
  12. for i := 0; i < b.N; i++ {
  13. _ = Add(1, 2)
  14. }
  15. }
  16. func main() {
  17. res := testing.Benchmark(BenchAdd)
  18. fmt.Printf("%s\n%#[1]v\n", res)
  19. }

产生的结果:

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

Playground

你可以使用ioutil.WriteFile将这些结果轻松写入文件。
Playground w/ WriteFile

英文:

For example:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;testing&quot;
  5. &quot;time&quot;
  6. )
  7. func Add(a, b int) int {
  8. time.Sleep(10 * time.Microsecond) // Just to make the test take some time
  9. return a + b
  10. }
  11. func BenchAdd(b *testing.B) {
  12. for i := 0; i &lt; b.N; i++ {
  13. _ = Add(1, 2)
  14. }
  15. }
  16. func main() {
  17. res := testing.Benchmark(BenchAdd)
  18. fmt.Printf(&quot;%s\n%#[1]v\n&quot;, res)
  19. }

Produces:

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

Playground.

You can easily write these results out to a file using ioutil.WriteFile.
Playground w/ WriteFile.

huangapple
  • 本文由 发表于 2015年1月20日 20:44:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/28045711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定