Golang基准测试设置数据库

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

Golang benchmark setup database

问题

我必须编写一些需要特定数据库设置的基准测试。类似这样的代码:

func BenchmarkXxx(b *testing.B) {
  fmt.Println("Setup")
  dropRecords()
  createDatabaseRecords() // 这需要很长时间

  fmt.Println("Start Test")
  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    fmt.Println("Loop")
    TestMyStuffs()
  }
}

运行这个基准测试,我可以在控制台看到"Setup"和"Start Test"被打印多次,所以BenchmarkXxx函数似乎被调用了多次。有没有办法只运行一次设置代码(例如这个例子中的createDatabaseRecords),并且只针对特定的基准测试运行?

有没有什么"最佳实践"来做到这一点?

英文:

I have to write some benchmarks that require a specific database setup. Something like this:

func BenchmarkXxx(b *testing.B) {
  fmt.Println(&quot;Setup&quot;)
  dropRecords()
  createDatabaseRecords() // this require a lot of time

  fmt.Println(&quot;Start Test&quot;)
  b.ResetTimer()
  for i := 0; i &lt; b.N; i++ {
    fmt.Println(&quot;Loop&quot;)
    TestMyStuffs()
  }
}

Running this benchmark I can see in the console that the "Setup" and "Start Test" are printing many times, so the BenchmarkXxx function seems to be called many times. Is there a way to run a setup code (createDatabaseRecords in this example) only one time and only for a specific benchmark?

Is there any sort of "best practice" to do this?

答案1

得分: 1

你可以使用子测试来处理这个案例,使用b.Run

func BenchmarkXxx(b *testing.B) {
	fmt.Println("设置")
	setup() // 这需要很长时间
	fmt.Println("开始测试")

	b.Run("mytest", func(b *testing.B) {
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			fmt.Println("循环")
			testMyStuffs()
		}
	})

}

子基准测试与其他基准测试一样。调用Run至少一次的基准测试本身不会被测量,并且将以N=1调用一次。

因此,BenchmarkXxx被调用一次,用于设置。

英文:

You can use sub-tests for this case, using b.Run

func BenchmarkXxx(b *testing.B) {
	fmt.Println(&quot;Setup&quot;)
	setup() // this require a lot of time
	fmt.Println(&quot;Start Test&quot;)

	b.Run(&quot;mytest&quot;, func(b *testing.B) {
		b.ResetTimer()
		for i := 0; i &lt; b.N; i++ {
			fmt.Println(&quot;Loop&quot;)
			testMyStuffs()
		}
	})

}

> A subbenchmark is like any other benchmark. A benchmark that calls Run at least once will not be measured itself and will be called once with N=1.

Thus BenchmarkXxx is called once, to do setup.

huangapple
  • 本文由 发表于 2022年9月20日 14:35:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73782483.html
匿名

发表评论

匿名网友

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

确定