package main import( "fmt" "time" "runtime" ) func fib(n uint64) uint64 { if n <= 2 { return 1 } return fib(n-1) + fib(n-2) } func pfib(n uint64) uint64 { if n <= 2 { // terminate recursion return 1 } // create a channel for subtask results res := make(chan uint64, 2) // fork 2 subtasks, they will send results to the res channel go func() { res <- fib(n - 1) }() go func() { res <- fib(n - 2) }() return <-res + <-res } func main(){ runtime.GOMAXPROCS(2) t0 := time.Now() fmt.Printf(" %d\n", pfib(48) ) t1 := time.Now() fmt.Printf("time %v to run.\n", t1.Sub(t0)) }
No comments:
Post a Comment