gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/httpsnoop/bench_test.go (about)

     1  package httpsnoop
     2  
     3  import (
     4  	"testing"
     5  
     6  	"gitee.com/ks-custle/core-gm/gmhttp/httptest"
     7  
     8  	http "gitee.com/ks-custle/core-gm/gmhttp"
     9  )
    10  
    11  func BenchmarkBaseline(b *testing.B) {
    12  	benchmark(b, false)
    13  }
    14  
    15  func BenchmarkCaptureMetrics(b *testing.B) {
    16  	benchmark(b, true)
    17  }
    18  
    19  func BenchmarkWrap(b *testing.B) {
    20  	b.StopTimer()
    21  	doneCh := make(chan struct{}, 1)
    22  	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    23  		b.StartTimer()
    24  		for i := 0; i < b.N; i++ {
    25  			Wrap(w, Hooks{})
    26  		}
    27  		doneCh <- struct{}{}
    28  	})
    29  	s := httptest.NewServer(h)
    30  	defer s.Close()
    31  	if _, err := http.Get(s.URL); err != nil {
    32  		b.Fatal(err)
    33  	}
    34  	<-doneCh
    35  }
    36  
    37  func benchmark(b *testing.B, captureMetrics bool) {
    38  	b.StopTimer()
    39  	dummyH := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
    40  	h := dummyH
    41  	if captureMetrics {
    42  		h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    43  			CaptureMetrics(dummyH, w, r)
    44  		})
    45  	}
    46  	s := httptest.NewServer(h)
    47  	defer s.Close()
    48  	b.StartTimer()
    49  	for i := 0; i < b.N; i++ {
    50  		_, err := http.Get(s.URL)
    51  		if err != nil {
    52  			b.Fatal(err)
    53  		}
    54  	}
    55  }