Skip to content

Instantly share code, notes, and snippets.

@djpnewton
Created October 11, 2011 04:30
Show Gist options
  • Save djpnewton/1277280 to your computer and use it in GitHub Desktop.
Save djpnewton/1277280 to your computer and use it in GitHub Desktop.
Testing scaling of parallelism in Go
package main
import (
"fmt"
"time"
"flag"
"runtime"
)
// basic fibonacci routine
func fib(n int) int {
if n <= 1 {
return n
}
return fib(n - 1) + fib(n - 2)
}
func fib_goroutine(n int, ch chan int) {
ch <- fib(n)
}
func main() {
n := flag.Int("n", 30, "The number to pass to the fib function")
c := flag.Int("c", 500, "The number of times to repeat the function")
p := flag.Int("p", 2, "The max number of CPU processors to use")
flag.Parse()
i := 0
ch := make(chan int)
// set maximum processor cores to use (see http://golang.org/doc/effective_go.html#parallel)
runtime.GOMAXPROCS(*p)
// run test
start := time.Nanoseconds()
for i = 0; i < *c; i++ {
go fib_goroutine(*n, ch)
}
for i = 0; i < *c; i++ {
<- ch
}
stop := time.Nanoseconds()
// print result
time_ := (stop - start) / 1e6
fmt.Printf("time = %dms", time_)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment