Instantly share code, notes, and snippets.

Embed
What would you like to do?
go rpc benchmark
package main
import (
"flag"
"fmt"
"log"
"net/rpc"
"sync"
"time"
)
var (
Num int
Conn int
Addr string
)
const RS = 100000
func init() {
flag.IntVar(&Num, "num", 1, "")
flag.IntVar(&Conn, "conn", 1, "")
flag.StringVar(&Addr, "addr", "127.0.0.1", "")
flag.Parse()
}
func main() {
clients := make([]*rpc.Client, 0, 10)
for i := 0; i < Conn; i++ {
client, err := rpc.Dial("tcp", Addr+":8000")
if err != nil {
log.Fatalln(err)
}
clients = append(clients, client)
}
index := 0
s1 := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
var wg sync.WaitGroup
start := time.Now()
for i := 0; i < Num; i++ {
wg.Add(1)
var c *rpc.Client
if index < len(clients) {
c = clients[index]
index++
} else {
index = 0
c = clients[index]
}
go func(cli *rpc.Client) {
defer wg.Done()
log.Println("goroutine start...")
st := time.Now()
for n := 0; n < RS; n++ {
if err := cli.Call("EchoServer.Echo", &s1, nil); err != nil {
log.Println(err)
}
}
log.Println(time.Now().Sub(st))
}(c)
}
wg.Wait()
total := RS * Num
secs := time.Now().Sub(start) / 1000000000
fmt.Printf("concurrency: %d\n", Num)
fmt.Printf("total: %d\n", total)
fmt.Printf("seconds: %d\n", secs)
fmt.Printf("qps: %d\n", total/int(secs))
}
package main
import (
"log"
"net"
"net/rpc"
)
type EchoServer bool
func (s *EchoServer) Echo(req *string, res *string) error {
return nil
}
func main() {
echo := new(EchoServer)
if err := rpc.Register(echo); err != nil {
log.Println(err)
return
}
var listener *net.TCPListener
if tcpAddr, err := net.ResolveTCPAddr("tcp", ":8000"); err != nil {
log.Println(err)
return
} else {
if listener, err = net.ListenTCP("tcp", tcpAddr); err != nil {
log.Println(err)
return
}
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
}
go rpc.ServeConn(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment