Created
May 11, 2014 04:33
-
-
Save klizhentas/7b4b58fe5918b25ccf26 to your computer and use it in GitHub Desktop.
Benchmark path router
This file contains hidden or 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 ( | |
"bytes" | |
"fmt" | |
. "github.com/mailgun/vulcan/location" | |
. "github.com/mailgun/vulcan/netutils" | |
. "github.com/mailgun/vulcan/request" | |
. "github.com/mailgun/vulcan/route/pathroute" | |
"io" | |
"math/rand" | |
"net/http" | |
"testing" | |
"time" | |
) | |
type rndString struct { | |
src rand.Source | |
} | |
func NewRndString() *rndString { | |
return &rndString{rand.NewSource(time.Now().UTC().UnixNano())} | |
} | |
func (r *rndString) Read(p []byte) (n int, err error) { | |
for i := range p { | |
p[i] = byte(r.src.Int63()%26 + 97) | |
} | |
return len(p), nil | |
} | |
func (r *rndString) MakeString(n int) string { | |
buffer := &bytes.Buffer{} | |
io.CopyN(buffer, r, int64(n)) | |
return buffer.String() | |
} | |
func testRouting(urls int) { | |
rndString := NewRndString() | |
m := NewPathRouter() | |
loc := &Loc{Name: "a"} | |
for i := 0; i < urls; i++ { | |
err := m.AddLocation(rndString.MakeString(rand.Intn(20)+10), loc) | |
if err != nil { | |
panic(err) | |
} | |
} | |
for i := 0; i < 100; i++ { | |
m.Route(request(fmt.Sprintf("http://google.com/%s", rndString.MakeString(rand.Intn(20)+10)))) | |
} | |
} | |
func benchmarkRouting(n int, b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
testRouting(n) | |
} | |
} | |
func benchmark1(b *testing.B) { | |
benchmarkRouting(1, b) | |
} | |
func benchmark100(b *testing.B) { | |
benchmarkRouting(100, b) | |
} | |
func benchmark1000(b *testing.B) { | |
benchmarkRouting(1000, b) | |
} | |
func main() { | |
result := testing.Benchmark(benchmark1) | |
fmt.Printf("1 Url: Iterations: %d, Time taken: %s\n", result.N, result.T) | |
result = testing.Benchmark(benchmark100) | |
fmt.Printf("100 Urls: Iterations: %d, Time taken: %s\n", result.N, result.T) | |
result = testing.Benchmark(benchmark1000) | |
fmt.Printf("1000 urls: Iterations: %d, Time taken: %s\n", result.N, result.T) | |
} | |
func request(url string) Request { | |
u := MustParseUrl(url) | |
return &BaseRequest{ | |
HttpRequest: &http.Request{URL: u}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment