Benchmark testing web applications

Much like unit testing, benchmark testing within Go is very simple, as Go provides a great abstraction. Also like unit testing, there is a strong convention for naming your benchmark tests. Benchmark tests need to include the word Benchmark at the beginning of the function name. In addition, the parameter expected is the *testing.B type instead of the *testing.T structure. Here is an example in which we benchmark our /health-check endpoint, which can be found in $GOPATH/src/github.com/PacktPublishing/Echo-Essentials/chapter7/handlers/health_check_test.go:

func BenchmarkHealthCheck(b *testing.B) {
        e := echo.New()
        e.Pre(middlewares.RequestIDMiddleware)
        e.GET("/health-check", HealthCheck)

        w := httptest.NewRecorder()
        r, _ := http.NewRequest("GET", "/health-check", nil)

        for i := 0; i < b.N; i++ {
                e.ServeHTTP(w, r)
        }
}

As seen here, our test starts out very similar to the unit test, we still need to create our Echo instance, and set up our /health-check endpoint. We must continue to create a response recorder, as well as a request to be served. Where the benchmark test diverges is the for loop. This for loop says, for b.N perform e.ServeHTTP. For the benchmark number of possible tries, run the handler code over and over again. The testing package will run this code within this for loop over and over, and increment b.N as it goes, until the testing package is satisfied that the benchmark is completed. This will run this e.ServeHTTP continually as fast as it can for a determined period of time. When we run the benchmark test shown next, we will get the amount of time required to perform the action:

go test -v ./... -bench Benchmark
=== RUN   TestHealthCheck
--- PASS: TestHealthCheck (0.00s)
goos: linux
goarch: amd64
pkg: github.com/PacktPublishing/Echo-Essentials/chapter7/handlers
BenchmarkHealthCheck-8            300000              5095 ns/op
PASS
ok      github.com/PacktPublishing/Echo-Essentials/chapter7/handlers  1.597s

As you can see, the time it took to run the HealthCheck handler was 5,095 nanoseconds, and in the 1.597 second run time we were able to perform 300K runs of the HealthCheck handler. With this benchmark in place, you will be able to alter your code, and know exactly how your alteration affects the performance of your service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.172.93