Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Created September 5, 2024 10:20
Show Gist options
  • Save pedrobertao/37491b25191f30ef4117e7bbac989473 to your computer and use it in GitHub Desktop.
Save pedrobertao/37491b25191f30ef4117e7bbac989473 to your computer and use it in GitHub Desktop.
fibonnaci performance
package main
import "fmt"
/*
* Fibonnaci's Number
* fb(pos)
* if n < 1
* f[0] = 1 f[1] =1
* else (n > 2)
* f[n] = sum(f[n-1] + f[n-2])
* -> 1 , 1 , 2 , 3 , 5, 8, 13
*/
func fibRecursive(position uint) uint {
if position <= 2 {
return 1
}
return fibRecursive(position-1) + fibRecursive(position-2)
}
func fibIterative(position uint) uint {
slc := make([]uint, position)
slc[0] = 1
slc[1] = 1
if position <= 2 {
return 1
}
var result, i uint
for i = 2; i < position; i++ {
result = slc[i-1] + slc[i-2]
slc[i] = result
}
return result
}
func main() {
pos := uint(8)
fmt.Printf("%d\n", (fibRecursive(pos)))
// Output = 21
fmt.Printf("%d\n", (fibIterative(pos)))
// Output = 21
}
// After that, create a main_test.go and use this code with these commands
// go test -bench=BenchmarkFibRecursive
// go test -bench=BenchmarkFibIterative
// package main
// import (
// "testing"
// )
// func BenchmarkFibIterative(b *testing.B) {
// for i := 0; i < b.N; i++ {
// fibIterative(uint(80))
// }
// }
// func BenchmarkFibRecursive(b *testing.B) {
// for i := 0; i < b.N; i++ {
// fibRecursive(uint(50))
// }
// }
import (
"testing"
)
// Use this command to run the benchmark
// go test -bench=BenchmarkFibRecursive
// go test -bench=BenchmarkFibIterative
func BenchmarkFibIterative(b *testing.B) {
for i := 0; i < b.N; i++ {
fibIterative(uint(80))
}
}
func BenchmarkFibRecursive(b *testing.B) {
for i := 0; i < b.N; i++ {
fibRecursive(uint(50))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment