简体   繁体   English

Golang 基准设置数据库

[英]Golang benchmark setup database

I have to write some benchmarks that require a specific database setup.我必须编写一些需要特定数据库设置的基准。 Something like this:像这样的东西:

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()
  }
}

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.运行这个基准测试我可以在控制台中看到“Setup”和“Start Test”打印了很多次,所以BenchmarkXxx function 似乎被调用了很多次。 Is there a way to run a setup code ( createDatabaseRecords in this example) only one time and only for a specific benchmark?有没有办法只运行一次设置代码(在本例中为createDatabaseRecords ),并且只针对特定的基准测试?

Is there any sort of "best practice" to do this?是否有任何“最佳实践”来做到这一点?

You can use sub-tests for this case, using b.Run对于这种情况,您可以使用子测试,使用b.Run

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

    b.Run("mytest", func(b *testing.B) {
        b.ResetTimer()
        for i := 0; i < b.N; i++ {
            fmt.Println("Loop")
            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.调用 Run 至少一次的基准测试本身不会被测量,并且会在 N=1 时调用一次。

Thus BenchmarkXxx is called once, to do setup.因此BenchmarkXxx被调用一次,进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM