Module 2: Benchmarking (The Stopwatch)
📚 Module 2: Benchmarking
Course ID: GO-302
Subject: The Stopwatch
Go makes it incredibly easy to see exactly how fast your code is. We use Benchmarks to measure performance in nanoseconds.
🏗️ Step 1: The Race
🧩 The Analogy: The Olympics
- You have two athletes (Two ways to solve a problem).
- You want to know which one is faster.
- You use a Stopwatch (Benchmark) to time them.
- To be fair, you have them run the same race 1 million times and take the average.
🏗️ Step 2: In Code
func BenchmarkAdd(b *testing.B) {
// b.N is automatically chosen by Go to be large enough
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}🏗️ Step 3: Running the Test
Run: go test -bench=.
📊 The Result:
BenchmarkAdd-8 1000000000 1.05 ns/op
- This means the code ran 1 billion times!
- Every single “Add” took only 1.05 nanoseconds.
🥅 Module 2 Review
- Benchmark: Measuring performance over many iterations.
- testing.B: The object used for benchmarking.
- ns/op: Nanoseconds per operation.
:::tip Senior Tip Go’s performance toolset is the best in the world. Use pprof (Advanced track) to see a 3D visualization of which function is stealing all your CPU time! ::: Riverside. Riverside.