Go Benchmarking: Measuring Function Performance
Benchmarking is crucial for optimizing Go code. This challenge asks you to implement a benchmarking suite for a simple function, allowing you to measure its execution time and identify potential bottlenecks. You'll learn how to use Go's built-in benchmarking tools to assess performance and compare different implementations.
Problem Description
You are tasked with creating a benchmarking suite for a function that calculates the nth Fibonacci number recursively. The function fibonacciRecursive(n int) int is provided. Your goal is to write a Go program that includes a benchmark test for this function. The benchmark should measure the execution time of fibonacciRecursive for various input values (e.g., 10, 20, 30). The benchmark results should be clear and easy to interpret, showing the average time taken per operation. Consider the limitations of recursive Fibonacci calculations and how benchmarking can highlight these.
Examples
Example 1:
Input: fibonacciRecursive(10)
Output: 55
Explanation: The 10th Fibonacci number is 55. This is a simple calculation to demonstrate the function's correctness.
Example 2:
Input: fibonacciRecursive(20)
Output: 6765
Explanation: The 20th Fibonacci number is 6765. This input will take longer to compute than the previous example.
Example 3: (Edge Case)
Input: fibonacciRecursive(0)
Output: 0
Explanation: The 0th Fibonacci number is 0. This is a base case for the recursion.
Constraints
- The benchmark should measure the execution time of
fibonacciRecursivefor at least three different input values (e.g., 10, 20, 30). - The benchmark results should be printed to the console in a readable format, including the input value and the average execution time in nanoseconds.
- The benchmark should be part of a Go test file (e.g.,
fibonacci_test.go). - The benchmark should be written using Go's built-in benchmarking framework (
testingpackage). - The
fibonacciRecursivefunction is provided and should not be modified.
Notes
- Go's benchmarking framework automatically runs the benchmarked function multiple times and calculates the average execution time.
- Consider the exponential time complexity of the recursive Fibonacci function. Larger input values will take significantly longer to compute.
- Use the
testing.Btype provided in the benchmark function to control the number of iterations and access timing information. - The
testing.Btype provides methods likeN(number of iterations) andResetTimer()(to exclude setup time from the benchmark). - Focus on writing a clear and concise benchmark that accurately measures the performance of the
fibonacciRecursivefunction.
package main
// fibonacciRecursive calculates the nth Fibonacci number recursively.
func fibonacciRecursive(n int) int {
if n <= 1 {
return n
}
return fibonacciRecursive(n-1) + fibonacciRecursive(n-2)
}