// Simple stupid concurrent Fibonacci microbenchmark. // On my laptop I get: // $ time ./concfib 30 // 1346269 // // real 0m7.673s // user 0m17.332s // sys 0m1.020s // // This is (/ 1346269 7.673) = 175k leaf calls per second, which is (/ // 64000 175.0) = 370 times slower than the version just using // function calls. It does use both cores of my CPU, and 5.7 // microseconds is substantially faster than fork/exit/wait for a C // program; forkovh.c measures that at 670 μs, over two orders of // magnitude worse. // // This program can compute fib(32) = 3524578 in 1.7 gigabytes of RAM, // suggesting that each goroutine needs less than a kilobyte. But // then, they aren’t all running at the same time. package main import ( "fmt" "os" "strconv" ) func fib(n int, ch chan int) { if n < 2 { ch <- 1 } else { a := make(chan int) b := make(chan int) go fib(n-1, a) go fib(n-2, b) ch <- <-a + <-b } } func main() { n, err := strconv.Atoi(os.Args[1]) if err != nil { panic(err) } ch := make(chan int) go fib(n, ch) fmt.Println(<-ch) }