用go 求解fib比较效率
go可以求解到45项都很快
package main
import (
"fmt"
"time"
)
func Fib(n int) int {
if n < 2 {
return n
}
return Fib(n-1) + Fib(n-2)
}
func single(size int) (int64, []int) {
st := time.Now().Unix()
ans := make([]int, size)
for i := 0; i < size; i++ {
ans[i] = Fib(i)
}
ed := time.Now().Unix()
return ed - st, ans
}
func FibMul(n int, c chan int) {
c <- Fib(n)
}
func Multiple(size int) (int64, []int) {
st := time.Now().Unix()
ans := make([]int, size)
c := make(chan int, size)
for i := 0; i < size; i++ {
go FibMul(i, c)
}
for i := 0; i < size; i++ {
ans[i] = <-c
}
ed := time.Now().Unix()
return ed - st, ans
}
func main() {
size := 45
t1, ans1 := single(size)
t2, ans2 := Multiple(size)
fmt.Println(t1, ans1)
fmt.Println(t2, ans2)
}
基本上能快一倍 5s 比js20多s快多了
11 [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733]
5 [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 1597 2584 4181 6765 987 17711 10946 75025 28657 46368 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733]
js
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2)
}
let ans = []
let st = +new Date()
for (let i = 0; i < 45; i++)
ans.push(fib(i))
let ed = +new Date()
console.log(ed - st, ans)
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/3211244