Here's a well-structured and idiomatic Go benchmark implementation that breaks each sec value into its own sub-benchmark. This allows for granular performance reporting for each input while maintaining clean and reusable code.
✅ Goal
- Create separate sub-benchmarks for each
sec value.
- Use Go's modern
Loop() method (introduced in Go 1.20).
- Keep memory allocations reporting consistent across all benchmarks.
✅ Final Code
func BenchmarkSecondsToTime(b *testing.B) {
// Define test cases with descriptive names and sec values
testCases := []struct {
name string
sec uint64
}{
{"1Hour", 3600}, // 1 hour
{"1_1Hour", 3960}, // 1.1 hours
{"3_1Hour", 11160}, // 3.1 hours
}
// Report allocations for the entire benchmark suite
b.ReportAllocs()
// Run a sub-benchmark for each test case
for _, tc := range testCases {
b.Run(tc.name, func(b *testing.B) {
// Use the modern Loop() method for benchmarking
for b.Loop() {
sink = secondsToTime(tc.sec)
}
})
}
}
✅ Explanation
- Test Cases: We define a slice of structs containing both the name of the sub-benchmark and the
sec value. This keeps the code DRY and makes it easy to add or remove cases.
- Sub-Benchmarks: We use
b.Run(name, func(b *testing.B)) to create a new sub-benchmark for each test case.
- Benchmark Loop: Inside each sub-benchmark, we use
b.Loop() which automatically handles the iteration count (b.N) and ensures accurate timing.
- Memory Allocation Reporting:
b.ReportAllocs() is called once at the top level to ensure all sub-benchmarks report allocations consistently.
✅ Expected Output
When running go test -bench=., you'll see output like:
BenchmarkSecondsToTime/1Hour
BenchmarkSecondsToTime/1_1Hour
BenchmarkSecondsToTime/3_1Hour
Each line will include timing and memory allocation statistics specific to that input.
This structure ensures clarity, maintainability, and precise performance measurement for each input scenario.