Created
September 5, 2024 10:20
-
-
Save pedrobertao/37491b25191f30ef4117e7bbac989473 to your computer and use it in GitHub Desktop.
fibonnaci performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
// } | |
// } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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