访问基准测试结果 [英] Accessing a benchmark's result
本文介绍了访问基准测试结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到Go中有一个结构 testing.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.
到目前为止,我仅对这样的功能进行基准测试:
So far I have only been benchmarking my functions like this:
func BenchmarkMyFunction(b *testing.B) {
// call to myFunction
}
然后运行:
go test -bench=".*"
这里将结果打印到控制台,但我想将它们存储在单独的文件中.如何使用BenchmarkResult
类型执行此操作?
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?
推荐答案
例如:
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{}}
游乐场.
您可以使用 ioutil.WriteFile
轻松地将这些结果写到文件中.
带有WriteFile的游乐场.
You can easily write these results out to a file using ioutil.WriteFile
.
Playground w/ WriteFile.
这篇关于访问基准测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文