Professional Documents
Culture Documents
benchmark tests for Golang code. Go promises fast performance, but how you
implement your code plays a big role in this. Improving the performance of your code
is worth your attention because it leads to lower server costs and faster-loading user
interfaces.
Below, I'm going to show you:
• how benchmarking works
• how we create a simple benchmark in Go
• steps to create and run a real-life, more complete, benchmark test
If you want to learn Golang quickly through building multiple real-world projects,
here's just about the fastest way to do so. The newline Guide to Reliable
Webservers with Golang is our comprehensive immersion in building practical
Golang web servers and other highly useful apps. It's taught by former Google and
Etsy engineers, Nat Welch and Steve McCarthy. You can get it here.
Benchmarks In A Nutshell
Benchmarking is a testing technique that helps you answer questions such as:
• "How fast does my code run?"
• "And if I make these changes to my code, will I get a significant performance
improvement?"
Benchmarks give us actual numbers that quantify the performance of our code:
• Execution Time - how much time does it take to run?
• Total Amount of Memory Allocated - how much memory must be allocated
for it to run?
• Rate of Memory Allocation - how many times must memory be allocated to
meet the total memory requirement?
Go's testing package contains benchmarking utilities for measuring these metrics.
Next, here's how we write the benchmark test for the Sum function.
// Import testing library
import (
"testing"
)
Similar to unit tests, benchmarks go in a file whose name ends with _test.go. To run
the benchmark, you invoke the go test command with the -bench=. flag.
go test -bench=.
Here, . tells Go to run all benchmarks within the package (i.e., main).
This benchmark runs the Sum function for b.N iterations. In this case, the benchmark
ran for one billion iterations. On average, each iteration ran 0.6199 ns.
$ make install_deps
$ make test
Our new benchmark will test the route handler for the GET /posts route.
// routes/posts_test.go
// ...
func BenchmarkGetPostsHandler(
b *testing.B) {
// Group benchmarks
b.Run(
"Endpoint: GET /posts",
func(b *testing.B) {
GetPosts = (
&JsonPlaceholderMock{}).GetPosts
We loop over handler.ServeHTTP until the benchmark determines how fast it runs.
The value of b.N changes until the benchmark stabilizes and knows how long it must
run to properly time the function.
Let's take a closer look at the flags in the above go test command.
P.S. Many engineers struggle to learn Golang, not because the language is too
difficult, but because they rely on incomplete, outdated blog posts. The newline
Guide to Reliable Webservers with Golang is the fastest way to proficiency with
Golang. See more here.
By the way, if you don't want to hear from me about Go, click here to opt-out of Go content, but stay
subscribed to the list.