Skip to content

Instantly share code, notes, and snippets.

@vmihailenco
Created August 31, 2012 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmihailenco/3550291 to your computer and use it in GitHub Desktop.
Save vmihailenco/3550291 to your computer and use it in GitHub Desktop.
bench2.go
package main
import (
"bytes"
"flag"
"fmt"
"log"
"net"
"os"
"runtime"
"runtime/pprof"
"time"
)
var request = []byte("PING\r\n")
var cpuProfile = flag.String("cpuprofile", "", "write cpu profile to file, e.g proxy.prof")
var w = flag.Int("w", 10, "worker number")
var dur = flag.Duration("time", 10*time.Second, "time to run benchmark")
func worker(counters chan int, exit chan int) {
counter := 0
conn, err := net.DialTimeout("tcp", ":6379", 3*time.Second)
if err != nil {
panic(err)
}
defer conn.Close()
reply := make([]byte, 100)
for {
select {
case <-exit:
counters <- counter
return
default:
_, err = conn.Write(request)
if err != nil {
panic(err)
}
n, err := conn.Read(reply)
if err != nil {
panic(err)
}
if !bytes.Equal(reply[:n], []byte("+PONG\r\n")) {
panic(`got "` + string(reply[:n]) + `", expected +PONG`)
}
counter++
}
}
}
func main() {
runtime.GOMAXPROCS(2)
flag.Parse()
if *cpuProfile != "" {
f, err := os.Create(*cpuProfile)
if err != nil {
log.Fatal(err)
}
err = pprof.StartCPUProfile(f)
if err != nil {
log.Fatal(err)
}
defer pprof.StopCPUProfile()
}
counters := make(chan int)
exits := make([]chan int, 0, *w)
for i := 0; i < *w; i++ {
exit := make(chan int)
exits = append(exits, exit)
go worker(counters, exit)
}
time.Sleep(*dur)
for _, exit := range exits {
exit <- 1
}
counter := 0
for i := 0; i < *w; i++ {
counter += <-counters
}
fmt.Printf("Requests: %v\n", counter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment