访问基准测试结果

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

Accessing a benchmark's result

问题

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

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

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

然后运行:

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:

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

And then running:

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

例如:

package main

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

func Add(a, b int) int {
	time.Sleep(10 * time.Microsecond) // 只是为了让测试花费一些时间
	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将这些结果轻松写入文件。
Playground w/ WriteFile

英文:

For example:

package main

import (
	&quot;fmt&quot;
	&quot;testing&quot;
	&quot;time&quot;
)

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 &lt; b.N; i++ {
		_ = Add(1, 2)
	}
}

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

Produces:

  120000	     10000 ns/op
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:

确定