Where to put setup/teardown in Go Benchmarks?

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

Where to put setup/teardown in Go Benchmarks?

问题

我在一个go的测试文件中编写了一个基准测试函数,代码如下:

func BenchmarkStuff(b *testing.B) {
    for i := 0; i < b.N; i++ {
        stuff()
    }
}

然而,stuff() 函数在每次运行之前都需要进行一些设置,并且在每次运行之后都需要进行清理。我有两个函数 setup()cleanup() 分别用于进行设置和清理操作。但是我不想对设置和清理函数进行基准测试。

那么它们应该在哪里调用呢?如果我在 BenchmarkStuff 函数内部调用它们,它们将会被计入结果测量中。但是如果没有它们,stuff() 函数将会失败。

英文:

I have a go test file in which I wrote a benchmark function as follows:

func BenchmarkStuff(b *testing.B) {
    for i := 0; i &lt; b.N; i++ {
        stuff()
    }
}

However the stuff() function requires some setup to occur every time before it runs and cleanup to occur every time after it runs. I have functions setup() and cleanup() that do this respectively. But I don't want to benchmark the setup and cleanup functions.

So where should they be called? If I call them inside BenchmarkStuff, they will be added to the results measurements. But without them, stuff() will fail.

答案1

得分: 20

基准测试包提供了ResetTimerStopTimerStartTimer方法,用于避免基准测试所需的计时初始化。

如果需要进行一次初始化,请在开始循环之前使用ResetTimer

func BenchmarkStuff(b *testing.B) {
    setup()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        stuff()
    }
}

如果需要在循环过程中重新初始化,可以使用StopTimerStartTimer来避免计时该部分:

func BenchmarkStuff(b *testing.B) {
    for i := 0; i < b.N; i++ {
        b.StopTimer()
        setup()
        b.StartTimer()
        stuff()
    }
}
英文:

The benchmarking package provides ResetTimer, StopTimer and StartTimer methods to avoid timing initialization needed for the benchmark.

If initialization is needed once, use ResetTimer before starting your loop:

func BenchmarkStuff(b *testing.B) {
    setup()
    b.ResetTimer()
    for i := 0; i &lt; b.N; i++ {
        stuff()
    }
}

If you need to re-initialize during the loop, you can use StopTimer and StartTimer to avoid timing that portion:

func BenchmarkStuff(b *testing.B) {
    for i := 0; i &lt; b.N; i++ {
        b.StopTimer()
        setup()
        b.StartTimer()
        stuff()
    }
}

huangapple
  • 本文由 发表于 2021年7月20日 05:22:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/68447175.html
匿名

发表评论

匿名网友

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

确定