douzhuo1853 2018-08-26 20:46
浏览 62
已采纳

为什么Benchmark运行六(?)次

This code (playground link):

package main

import (
    "fmt"
    "testing"
)

var test = make([]int, 0)

func main() {
    fmt.Println(testing.Benchmark(testThis))
}

func testThis(b *testing.B) {
    fmt.Println(test)
}

has next output:

[]
[]
[]
[]
[]
[]
2000000000           0.00 ns/op

Program exited.

Why there are six [] inside output?

This code (playground link):

package main

import (
    "fmt"
)

var test = make([]int, 0)

func main() {
    fmt.Println(test)
}

has single output (and it's clear for me):

[]

Program exited.
  • 写回答

1条回答 默认 最新

  • douchongbang6011 2018-08-26 21:08
    关注

    You are using a benchmark function. This need to execute code multiple times to get a result which is kinda meaningful.

    Also your Benchmark is not implemented like the benchmark should be programmed:

    The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. -- https://golang.org/pkg/testing/

    So Benchmark will check the run time and will adjust the b.N to get a good and useful benchmark.

    When you just print b.N you get an output like this:

    1
    100
    10000
    1000000
    100000000
    2000000000
    2000000000  
    

    So in each of the 6 iterations the benchmark is telling you to run a foor loop b.N times.

    Sadly you can not use a correct example in the playground because they take to long. But correct would be:

    func testThis(b *testing.B) {
        for i := 0; i < b.N; i++ {
            fmt.Println(test)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程