Skip to content

Instantly share code, notes, and snippets.

@cshenton
Last active September 4, 2018 14:59
Show Gist options
  • Save cshenton/b7d694dc152954428924b73a6fab5078 to your computer and use it in GitHub Desktop.
Save cshenton/b7d694dc152954428924b73a6fab5078 to your computer and use it in GitHub Desktop.
// This program starts N goroutines which each generate numSteps random
// numbers and prints the amount of time it takes.
//
// See if you can you figure out why it doesn't parallelise properly.
package main
import (
"fmt"
"math/rand"
"time"
)
const numSteps = 1e6
func run(numProcs int) {
t := time.Now()
ch := make(chan bool)
for i := 0; i < numProcs; i++ {
go func() {
for i := 0; i < numSteps; i++ {
_ = rand.Float64()
}
ch <- true
}()
}
for i := 0; i < numProcs; i++ {
<-ch
}
fmt.Println(time.Now().Sub(t))
}
func main() {
// These "should" all be equally fast if we have a multicore machine.
// But they scale super-linearly with numProcs.
run(1) // 20.318803ms
run(2) // 46.067529ms
run(4) // 154.362519ms
run(8) // 411.398554ms
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment