Writing benchmarks
Similar to a unit test, benchmarks are stored in the _test.go
files, but these functions start with Benchmark
instead of Test
. A benchmark is given a number N
where you repeat the same operation N
times while the runtime is measuring the performance.
How to do it...
- Create a benchmark function in one of the
_test.go
files. The following example is in thesort_test.go
file:func BenchmarkSortAscending(b *testing.B) {
- Do the setup before the benchmark loop, otherwise, you will be benchmarking the setup code as well, not the actual algorithm:
input := []time.Time{ time.Date(2023, 2, 1, 12, 8, 37, 0, time.Local), time.Date(2021, 5, 6, 9, 48, 11, 0, time.Local), time.Date(2022, 11, 13, 17, 13, 54, 0, time.Local), time.Date(2022, 6, 23, 22, 29, 28, 0, time.Local), time.Date(2023, 3, 17, 4, 5, 9, 0, time.Local), }
- Write a
for
loop iteratingb.N
times and perform the operation that will be benchmarked...