github.com/searKing/golang/go@v1.2.117/net/mux/bench_test.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mux_test 6 7 import ( 8 "context" 9 "io" 10 "net" 11 "testing" 12 "time" 13 14 "github.com/searKing/golang/go/net/mux" 15 "github.com/searKing/golang/go/testing/leakcheck" 16 17 "golang.org/x/net/http2" 18 ) 19 20 var ( 21 benchHTTP1Payload = make([]byte, 4096) 22 benchHTTP2Payload = make([]byte, 4096) 23 ) 24 25 func init() { 26 copy(benchHTTP1Payload, "GET http://www.w3.org/ HTTP/1.1") 27 copy(benchHTTP2Payload, http2.ClientPreface) 28 } 29 30 type mockConn struct { 31 net.Conn 32 r io.Reader 33 } 34 35 func (c *mockConn) Read(b []byte) (n int, err error) { 36 return c.r.Read(b) 37 } 38 39 func (c *mockConn) SetReadDeadline(time.Time) error { 40 return nil 41 } 42 43 func discard(ctx context.Context, l net.Listener) { 44 for { 45 select { 46 case <-ctx.Done(): 47 return 48 default: 49 } 50 c, err := l.Accept() 51 if err != nil { 52 return 53 } 54 c.Close() 55 } 56 } 57 58 func run(ctx context.Context, m *mux.Server, matchers ...mux.Matcher) { 59 60 serveMux := mux.NewServeMux() 61 for _, matcher := range matchers { 62 l := serveMux.HandleListener(matcher) 63 go func() { 64 _ = m.Serve(l) 65 defer l.Close() 66 }() 67 68 go discard(ctx, l) 69 } 70 } 71 72 func BenchmarkCMuxConnHTTP1(b *testing.B) { 73 defer leakcheck.Check(b) 74 m := mux.NewServer() 75 defer m.Close() 76 lis := testListener(b) 77 defer lis.Close() 78 ctx, cancelFn := context.WithCancel(context.TODO()) 79 defer cancelFn() 80 81 b.ResetTimer() 82 b.RunParallel(func(pb *testing.PB) { 83 for pb.Next() { 84 run(ctx, m, mux.HTTP1Fast()) 85 } 86 }) 87 } 88 89 func BenchmarkCMuxConnHTTP2(b *testing.B) { 90 defer leakcheck.Check(b) 91 m := mux.NewServer() 92 defer m.Close() 93 lis := testListener(b) 94 defer lis.Close() 95 ctx, cancelFn := context.WithCancel(context.TODO()) 96 defer cancelFn() 97 98 b.ResetTimer() 99 b.RunParallel(func(pb *testing.PB) { 100 for pb.Next() { 101 run(ctx, m, mux.HTTP2()) 102 } 103 }) 104 } 105 func BenchmarkCMuxConnHTTP1n2(b *testing.B) { 106 defer leakcheck.Check(b) 107 m := mux.NewServer() 108 defer m.Close() 109 lis := testListener(b) 110 defer lis.Close() 111 ctx, cancelFn := context.WithCancel(context.TODO()) 112 defer cancelFn() 113 114 b.ResetTimer() 115 b.RunParallel(func(pb *testing.PB) { 116 for pb.Next() { 117 run(ctx, m, mux.HTTP1Fast()) 118 run(ctx, m, mux.HTTP2()) 119 } 120 }) 121 } 122 123 func BenchmarkCMuxConnHTTP2n1(b *testing.B) { 124 defer leakcheck.Check(b) 125 m := mux.NewServer() 126 defer m.Close() 127 lis := testListener(b) 128 defer lis.Close() 129 ctx, cancelFn := context.WithCancel(context.TODO()) 130 defer cancelFn() 131 132 b.ResetTimer() 133 b.RunParallel(func(pb *testing.PB) { 134 for pb.Next() { 135 run(ctx, m, mux.HTTP2()) 136 run(ctx, m, mux.HTTP1Fast()) 137 } 138 }) 139 }