Golang 基准设置数据库

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


func BenchmarkXxx(b *testing.B) {

  fmt.Println("Setup")

  dropRecords()

  createDatabaseRecords() // this require a lot of time


  fmt.Println("Start Test")

  b.ResetTimer()

  for i := 0; i < b.N; i++ {

    fmt.Println("Loop")

    TestMyStuffs()

  }

}

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


是否有任何类型的“最佳实践”来做到这一点?


www说
浏览 111回答 1
1回答

撒科打诨

您可以使用b.Run对这种情况使用子测试func BenchmarkXxx(b *testing.B) {&nbsp; &nbsp; fmt.Println("Setup")&nbsp; &nbsp; setup() // this require a lot of time&nbsp; &nbsp; fmt.Println("Start Test")&nbsp; &nbsp; b.Run("mytest", func(b *testing.B) {&nbsp; &nbsp; &nbsp; &nbsp; b.ResetTimer()&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Loop")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; testMyStuffs()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}子基准与任何其他基准一样。至少调用一次 Run 的基准将不会对其自身进行测量,并且将在 N=1 时调用一次。因此BenchmarkXxx被调用一次,进行设置。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go