Created
December 6, 2021 11:01
-
-
Save aarzilli/f0dc44622d93f402fc4046c02fb117c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"runtime" | |
"runtime/pprof" | |
_ "runtime/trace" | |
"fmt" | |
"time" | |
"os" | |
) | |
type in struct { | |
c chan *out | |
arg int | |
} | |
type out struct { | |
ret int | |
} | |
func compute(arg int) int { | |
return 3+arg | |
} | |
func unlockedServer(c chan *in) { | |
for r := range c { | |
r.c <- &out{ret: compute(r.arg)} | |
} | |
} | |
func lockedServer(c chan *in) { | |
runtime.LockOSThread() | |
defer runtime.UnlockOSThread() | |
for r := range c { | |
r.c <- &out{ret: compute(r.arg)} | |
} | |
} | |
func client(c chan *in, arg int) int { | |
rc := make(chan *out) | |
c <- &in{ | |
c: rc, | |
arg: arg, | |
} | |
ret := <-rc | |
return ret.ret | |
} | |
const N = 100000 | |
func benchmark(name string, server func(chan *in)) { | |
c := make(chan *in) | |
go server(c) | |
t0 := time.Now() | |
for i := 0; i < N; i++ { | |
client(c, i) | |
} | |
d := time.Since(t0) | |
ds := float64(d) / float64(time.Second) | |
fmt.Printf("%s\t%.10f (%v) (total=%.5f)\n", name, ds/N, d/N, ds) | |
} | |
func main() { | |
f, err := os.Create("example.com.pprof") | |
if err != nil { | |
panic(err) | |
} | |
pprof.StartCPUProfile(f) | |
defer pprof.StopCPUProfile() | |
/* | |
f2, err := os.Create("example.com.trace") | |
if err != nil { | |
panic(err) | |
} | |
trace.Start(f2) | |
defer trace.Stop() | |
*/ | |
switch os.Args[1] { | |
case "unlocked": | |
benchmark("unlocked", unlockedServer) | |
case "locked": | |
benchmark("locked", lockedServer) | |
case "locked2": | |
runtime.LockOSThread() | |
defer runtime.UnlockOSThread() | |
benchmark("locked2", lockedServer) | |
default: | |
panic("blah") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment