在 golang 中运行没有“go test”的基准测试

3 testing benchmarking go

我想在我的应用程序中运行基准测试。那可能吗?如果是这样,我该怎么办?我一直在环顾四周,但到目前为止还没有看到任何迹象。

mko*_*iva 5

您可以使用testing.Benchmark而无需运行go test.

package main

import (
    "fmt"
    "testing"
)

func Fib(n int) int {
    if n <= 0 {
        return 0
    } else if n == 1 {
        return 1
    }
    return Fib(n-1) + Fib(n-2)
}

func main() {
    res := testing.Benchmark(func(b *testing.B) {
        for n := 0; n < b.N; n++ {
            Fib(10)
        }
    })
    fmt.Println(res)
    // (on my mac)
    // 3000000               454 ns/op
}
Run Code Online (Sandbox Code Playgroud)