Skip to content

Instantly share code, notes, and snippets.

@illia-danko
Last active March 6, 2019 00:32
Show Gist options
  • Save illia-danko/d6a7f741fde27f5dc0d8362a3be8d4db to your computer and use it in GitHub Desktop.
Save illia-danko/d6a7f741fde27f5dc0d8362a3be8d4db to your computer and use it in GitHub Desktop.
Golang benchmark test to compare two built-in Gob and Json RPC servers.
// The purpose of this source file is to compare transmittion speed of two
// built-in RPCs servers, namely Gob and Json by using blocking calls.
package main
import (
"net"
"net/rpc"
"net/rpc/jsonrpc"
"testing"
)
const (
address = "localhost:10080"
waste = 1000000
)
const (
param1 = "Hello "
param2 = "World"
)
type StringOpsConcatArgs struct {
Param1 string
Param2 string
}
type StringOps struct{}
func (so *StringOps) Concat(args *StringOpsConcatArgs, response *string) error {
for i := 0; i < waste; i++ {
(*response) = args.Param1 + args.Param2
}
return nil
}
func initGobServer(t *testing.B) {
server := rpc.NewServer()
server.Register(new(StringOps))
server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
listener, err := net.Listen("tcp", address)
if err != nil {
t.Error(err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
t.Error(err)
}
server.ServeConn(conn)
}
}()
t.Log("Gob RPC server is runnig")
}
func clientCall(testType, rpcMethod string, c *rpc.Client, t *testing.B) {
var resultTok string
ok := t.Run(testType, func(test *testing.B) {
for i := 0; i < t.N; i++ {
err := c.Call(rpcMethod, StringOpsConcatArgs{param1, param2}, &resultTok)
if err != nil {
test.Error(err)
}
t.Log(resultTok)
}
})
if !ok {
t.Error("error: unsuccessful")
}
}
func mustDial() net.Conn {
conn, err := net.Dial("tcp", address)
if err != nil {
panic(err)
}
return conn
}
func BenchmarkRPCGob(t *testing.B) {
initGobServer(t)
clientCall("gobRpc", "StringOps.Concat", rpc.NewClient(mustDial()), t)
}
func initJsonServer(t *testing.B) {
server := rpc.NewServer()
server.Register(new(StringOps))
server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
listener, err := net.Listen("tcp", address)
if err != nil {
t.Error(err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
t.Error(err)
}
server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}()
t.Log("Json RPC server is runnig")
}
func BenchmarkRPCJson(t *testing.B) {
initJsonServer(t)
clientCall("jsonRpc", "StringOps.Concat", jsonrpc.NewClient(mustDial()), t)
}
@illia-danko
Copy link
Author

Verdict: mostly same metrics on MacBook Pro (4x2) machine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment