Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bohdantrotsenko/85776afd61c3d37169e1f136404e5689 to your computer and use it in GitHub Desktop.
Save bohdantrotsenko/85776afd61c3d37169e1f136404e5689 to your computer and use it in GitHub Desktop.
Demonstrates that heavy cpu functions steal time from IO goroutines
package main
import (
"fmt"
"time"
"net/http"
"net"
)
const N = 300
const P = 20
const timeFormat = "15:04:05.0000"
func heavy(res chan<- string) {
start := time.Now()
var sum int64 = 0
for i1 := 0; i1 < N; i1++ {
for i2 := 0; i2 < N; i2++ {
for i3 := 0; i3 < N; i3++ {
for i4 := 0; i4 < N; i4++ {
sum++
}
}
}
}
n := int64(N)
n = n * n
n = n * n
if sum != n {
fmt.Println("Ooops")
}
end := time.Now()
dur := end.Sub(start)
res <- fmt.Sprintf("started %s, ended %s (lasted %f)", start.Format(timeFormat), end.Format(timeFormat), dur.Seconds())
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
str := fmt.Sprintf("The time is %s", time.Now().String())
w.Write(([]byte)(str))
})
listener, _ := net.Listen("tcp", "localhost:7777")
go http.Serve(listener, mux)
res := make(chan string, P)
for i := 0; i < P; i++ {
go heavy(res)
}
fmt.Println(">>>")
for {
fmt.Println(<-res)
go heavy(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment