benchmarks_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package gin
  2. import (
  3. "log"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func runHandler(B *testing.B, handler HandlerFunc) {
  9. req, err := http.NewRequest("GET", "http://localhost/foo", nil)
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. c := &Context{
  14. Writer: &responseWriter{httptest.NewRecorder(), 0, false},
  15. Req: req,
  16. index: 0,
  17. }
  18. B.ReportAllocs()
  19. B.ResetTimer()
  20. for i := 0; i < B.N; i++ {
  21. c.index = 0
  22. handler(c)
  23. }
  24. }
  25. func runRequest(B *testing.B, r *Engine, path string) {
  26. // create fake request
  27. url := "http://localhost" + path
  28. req, err := http.NewRequest("GET", url, nil)
  29. if err != nil {
  30. panic(err)
  31. }
  32. // create fake writes
  33. w := httptest.NewRecorder()
  34. B.ReportAllocs()
  35. B.ResetTimer()
  36. for i := 0; i < B.N; i++ {
  37. r.ServeHTTP(w, req)
  38. }
  39. }
  40. func BenchmarkMiddlewareLogger(B *testing.B) {
  41. runHandler(B, Logger())
  42. }
  43. func BenchmarkDefaultOnlyPing(B *testing.B) {
  44. r := New()
  45. r.GET("/ping", func(c *Context) {
  46. c.String(200, "pong")
  47. })
  48. runRequest(B, r, "/ping")
  49. }
  50. func BenchmarkDefaultPing(B *testing.B) {
  51. r := Default()
  52. r.GET("/ping", func(c *Context) {
  53. c.String(200, "pong")
  54. })
  55. runRequest(B, r, "/ping")
  56. }