Benchmarking, Accessing and Listening

This lesson provides an explanation on how to benchmark a goroutine, run a backend goroutine, and use reflection on channels.

Benchmarking goroutines

In Chapter 11, we mentioned the principle of performing benchmarks on your functions in Go. Here, we apply it to a concrete example of a goroutine that is filled with ints and then read. The functions are called N times (e.g. N =1000000) with testing.Benchmark. The BenchMarkResult has a String() method for outputting its findings. The number N is decided upon by go test. It is taken to be high enough to get a reasonable benchmark result.

Of course, the same way of benchmarking also applies to ordinary functions. If you want to exclude certain parts of the code or you want to be more specific in what you are timing, you can stop and start the timer by calling the functions testing.B.StopTimer() and testing.B.StartTimer() as appropriate. The benchmarks will only be run if all your tests pass!

Get hands-on with 1200+ tech skills courses.