Skip to content

Instantly share code, notes, and snippets.

@cshenton
Last active September 4, 2018 15:34
Show Gist options
  • Save cshenton/9f4d0027cd0ad2ad8fd9fa44bce9a48b to your computer and use it in GitHub Desktop.
Save cshenton/9f4d0027cd0ad2ad8fd9fa44bce9a48b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
)
// This program starts numProcs goroutines which each generate numSteps random
// numbers and prints the amount of time it takes.
//
// It scales perfectly on an i9 until we reach the number of cores, 6 (yes we have
// 12 hyperthreads but each pair shares a floating point core).
const numSteps = 1e6
func run(numProcs int) {
t := time.Now()
ch := make(chan bool)
for i := 0; i < numProcs; i++ {
go func() {
// Generate a rand source for the thread.
// Instead of accessing the threadsafe default source.
// Which causes a lot of lock contention!
r := rand.New(rand.NewSource(rand.Int63()))
for i := 0; i < numSteps; i++ {
_ = r.Float64()
}
ch <- true
}()
}
for i := 0; i < numProcs; i++ {
<-ch
}
fmt.Println(time.Now().Sub(t))
}
func main() {
// Better!
run(1) // 7.475166ms
run(2) // 6.727281ms
run(4) // 6.186384ms
run(6) // 6.240453ms
run(8) // 12.316837ms
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment