英文:
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=".*"
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{}}
你可以使用ioutil.WriteFile
将这些结果轻松写入文件。
Playground w/ WriteFile。
英文:
For example:
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)
}
Produces:
120000 10000 ns/op
testing.BenchmarkResult{N:120000, T:1200000000, Bytes:0, MemAllocs:0x0, MemBytes:0x0, Extra:map[string]float64{}}
You can easily write these results out to a file using ioutil.WriteFile
.
Playground w/ WriteFile.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论