在Golang中不使用”go test”运行基准测试。

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

Running benchmarks without "go test" in golang

问题

我想在我的应用程序中运行基准测试。这可能吗?如果可以,我该如何操作?我一直在寻找相关信息,但目前还没有看到任何迹象。

英文:

I want to run the benchmarks in my application. Is that possible? If so, how can I? I have been looking around but haven't seen any indication so far.

答案1

得分: 6

你可以在不运行go test的情况下使用testing.Benchmark

  1. package main
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func Fib(n int) int {
  7. if n <= 0 {
  8. return 0
  9. } else if n == 1 {
  10. return 1
  11. }
  12. return Fib(n-1) + Fib(n-2)
  13. }
  14. func main() {
  15. res := testing.Benchmark(func(b *testing.B) {
  16. for n := 0; n < b.N; n++ {
  17. Fib(10)
  18. }
  19. })
  20. fmt.Println(res)
  21. // (在我的 Mac 上)
  22. // 3000000 454 ns/op
  23. }

以上是你要翻译的内容。

英文:

You can use testing.Benchmark without running go test.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;testing&quot;
  5. )
  6. func Fib(n int) int {
  7. if n &lt;= 0 {
  8. return 0
  9. } else if n == 1 {
  10. return 1
  11. }
  12. return Fib(n-1) + Fib(n-2)
  13. }
  14. func main() {
  15. res := testing.Benchmark(func(b *testing.B) {
  16. for n := 0; n &lt; b.N; n++ {
  17. Fib(10)
  18. }
  19. })
  20. fmt.Println(res)
  21. // (on my mac)
  22. // 3000000 454 ns/op
  23. }

huangapple
  • 本文由 发表于 2017年4月14日 06:06:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/43402469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定