github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/apiserverhttp/mux_bench_test.go (about)

     1  // Copyright 2018 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package apiserverhttp_test
     5  
     6  import (
     7  	"io"
     8  	"net/http"
     9  	"sync"
    10  
    11  	"github.com/bmizerany/pat"
    12  	"github.com/juju/testing"
    13  	gc "gopkg.in/check.v1"
    14  
    15  	"github.com/juju/juju/apiserver/apiserverhttp"
    16  )
    17  
    18  type MuxBenchSuite struct {
    19  	testing.IsolationSuite
    20  }
    21  
    22  var _ = gc.Suite(&MuxBenchSuite{})
    23  
    24  func (s *MuxBenchSuite) BenchmarkMux(c *gc.C) {
    25  	mux := apiserverhttp.NewMux()
    26  	mux.AddHandler("GET", "/hello/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
    27  	s.benchmarkMux(c, mux)
    28  }
    29  
    30  func (s *MuxBenchSuite) BenchmarkPatMux(c *gc.C) {
    31  	mux := pat.New()
    32  	mux.Add("GET", "/hello/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
    33  	s.benchmarkMux(c, mux)
    34  }
    35  
    36  func (s *MuxBenchSuite) benchmarkMux(c *gc.C, mux http.Handler) {
    37  	req := newRequest("GET", "/hello/blake", nil)
    38  	c.ResetTimer()
    39  	var wg sync.WaitGroup
    40  	for i := 0; i < 100; i++ {
    41  		wg.Add(1)
    42  		go func() {
    43  			defer wg.Done()
    44  			for n := 0; n < c.N; n++ {
    45  				mux.ServeHTTP(nil, req)
    46  			}
    47  		}()
    48  	}
    49  	wg.Wait()
    50  }
    51  
    52  func newRequest(method, urlStr string, body io.Reader) *http.Request {
    53  	req, err := http.NewRequest(method, urlStr, body)
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  	return req
    58  }