From 1abc373affbecd6f3bfcdf34f6da03435acdb0a5 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Fri, 4 Jul 2014 18:37:17 +0200 Subject: [PATCH] Some work around benchmarks --- benchmarks_test.go | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 benchmarks_test.go diff --git a/benchmarks_test.go b/benchmarks_test.go new file mode 100644 index 00000000..060f8132 --- /dev/null +++ b/benchmarks_test.go @@ -0,0 +1,64 @@ +package gin + +import ( + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func runHandler(B *testing.B, handler HandlerFunc) { + req, err := http.NewRequest("GET", "http://localhost/foo", nil) + if err != nil { + log.Fatal(err) + } + c := &Context{ + Writer: &responseWriter{httptest.NewRecorder(), 0, false}, + Req: req, + index: 0, + } + + B.ReportAllocs() + B.ResetTimer() + for i := 0; i < B.N; i++ { + c.index = 0 + handler(c) + } +} + +func runRequest(B *testing.B, r *Engine, path string) { + // create fake request + url := "http://localhost" + path + req, err := http.NewRequest("GET", url, nil) + if err != nil { + panic(err) + } + // create fake writes + w := httptest.NewRecorder() + + B.ReportAllocs() + B.ResetTimer() + for i := 0; i < B.N; i++ { + r.ServeHTTP(w, req) + } +} + +func BenchmarkMiddlewareLogger(B *testing.B) { + runHandler(B, Logger()) +} + +func BenchmarkDefaultOnlyPing(B *testing.B) { + r := New() + r.GET("/ping", func(c *Context) { + c.String(200, "pong") + }) + runRequest(B, r, "/ping") +} + +func BenchmarkDefaultPing(B *testing.B) { + r := Default() + r.GET("/ping", func(c *Context) { + c.String(200, "pong") + }) + runRequest(B, r, "/ping") +}