douqiaolong0528 2018-11-15 15:39
浏览 499
已采纳

可以限制Go Benchmarking中的迭代次数(b.N)吗?

I'm trying to benchmark an operation which requires expensive preparation which I'm excluding using StopTimer() and StartTimer(). Specifically, I'm benchmarking nth-item insertion into a sorted list.

Sample code:

n := 100

// Run the process b.N times
for i := 0; i < b.N; i++ {

    // Stop the timer for our expensive preparation work (inserting n-1 items)
    b.StopTimer()

    // ...

    // Insert n-1 items
    for j := 1; j < n; j++ {
        m.InsertItem(o)
    }

    // ...

    // Resume the timer
    b.StartTimer()

    // Insert the nth item
    m.InsertItem(o)

}

The problem is that Go's benchmarking heuristic is limiting b.N according to the benchmarked time, not the total time. It ends up asking for 5MM (5000000) iterations of 100th order insertion, and this takes more time than is reasonable (I want to benchmark up to the 10 millionth item insertion).

Is there a way to specify a maximum b.N for a specific benchmark in Go's benchmark tool? I did not find anything in the docs myself.

  • 写回答

1条回答 默认 最新

  • dongzhimin2231 2018-11-15 16:22
    关注

    -benchtime flag can be used to specify the time for which you want to run the benchmark(source). Although I haven't tried it, providing a lower value of time than 1 sec should do the trick.

    go test -bench=. -benchtime=10s

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧