英文:
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 < 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
基准测试包提供了ResetTimer
、StopTimer
和StartTimer
方法,用于避免基准测试所需的计时初始化。
如果需要进行一次初始化,请在开始循环之前使用ResetTimer
:
func BenchmarkStuff(b *testing.B) {
setup()
b.ResetTimer()
for i := 0; i < b.N; i++ {
stuff()
}
}
如果需要在循环过程中重新初始化,可以使用StopTimer
和StartTimer
来避免计时该部分:
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 < 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 < b.N; i++ {
b.StopTimer()
setup()
b.StartTimer()
stuff()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论