11.4 Benchmark
Functions
Benchmarking is the practice of measuring the performance of a program
on a fixed workload.
In Go, a benchmark function looks like a test function, but with the
Benchmark
prefix and a *testing.B
parameter that
provides most
of the same methods as a *testing.T
, plus a few extra related to performance
measurement.
It also exposes an integer field N
, which specifies the number
of times to perform the operation being measured.
Here’s a benchmark for IsPalindrome
that calls it N
times in
a loop.
import "testing" func BenchmarkIsPalindrome(b *testing.B) { for i := 0; i < b.N; i++ { IsPalindrome("A man, a plan, a canal: Panama") } }
We run it with the command below. Unlike tests, by default ...
Get The Go Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.