Go: fib
Go code is relatively low-level since it does not have "foreach over range" syntax construct:
Results are not as impressive for a systems language: 2.38 seconds. And it lays below Rust but under Haskell:
This file contains 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" | |
"time" | |
) | |
func fib(n int) int { | |
if n < 2 { | |
return n | |
} | |
return fib(n-1) + fib(n-2) | |
} | |
func main() { | |
start := time.Now() | |
for n := 0; n < 40; n++ { | |
fmt.Printf("fib (%d) = %d\n", n, fib(n)) | |
} | |
fmt.Printf("Elapsed %s", time.Since(start)) | |
} |
- C# - 1.26
- D (DMD) - 1.3
- F# - 1.38
- Nemerle - 1.45
- Rust - 1.66
- Go - 2.38
- Haskell - 2.8
- Clojure - 9
- Erlang - 17
- Ruby - 60
- Python - 120
Comments
#include
#include
int fib(int n){
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
clock_t begin = clock();
for (int n = 0; n < 40; n++) {
printf("fib (%d) = %d\n", n, fib(n));
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
printf("elapsed: %f secs\n", elapsed_secs);
return 0;
}