访问基准测试结果

问题描述 投票:0回答:1

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

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

testing.BenchmarkResult

然后运行:

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

这里将结果打印到控制台,但我想将它们存储在单独的文件中。如何使用go test -bench=".*" 类型执行此操作?

go benchmarking
1个回答
3
投票

例如:

BenchmarkResult

产品:

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

© www.soinside.com 2019 - 2024. All rights reserved.