Skip to content

Instantly share code, notes, and snippets.

@raedwulf
Created October 22, 2016 20:43
Show Gist options
  • Save raedwulf/e6bbb76a3becb5fa14eb27e670260b1b to your computer and use it in GitHub Desktop.
Save raedwulf/e6bbb76a3becb5fa14eb27e670260b1b to your computer and use it in GitHub Desktop.
Context switch benchmark in Go
import (
"fmt"
"time"
"flag"
"strconv"
"runtime"
)
func worker(count int) {
for i := 0; i != count; i++ {
runtime.Gosched()
}
}
func main() {
flag.Parse()
count, _ := strconv.Atoi(flag.Arg(0))
count = count * 1000000 / 2
start := time.Now()
go worker(count)
for i := 0; i != count; i++ {
runtime.Gosched()
}
stop := time.Now()
duration := stop.Sub(start)
ns := duration.Nanoseconds() / int64(count)
fmt.Printf("performed %dM context switches in %f seconds\n", count * 2 / 1000000, duration.Seconds())
fmt.Printf("duration of one context switch: %d ns\n", ns)
fmt.Printf("context switches per second: %fM\n", float32(1000000000 / ns) / 1000000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment