Code benchmark
The purpose of benchmarking is to measure a code's performance. The Go test command-line tool comes with support for the automated generation and measurement of benchmark metrics. Similar to unit tests, the test tool uses benchmark functions to specify what portion of the code to measure. The benchmark function uses the following function naming pattern and signature:
func Benchmark<Name>(*testing.B)
Benchmark functions are expected to have names that start with benchmark and accept a pointer value of type *testing.B
. The following shows a function that benchmarks the Add
method for type SimpleVector
(introduced earlier):
import ( "math/rand" "testing" "time" ) ... func BenchmarkVectorAdd(b *testing.B) { r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < b.N; i++ { v1 := New(r.Float64(), r.Float64()) v2 := New(r.Float64(), r.Float64()) v1.Add(v2) } }
golang...