github.com/metacubex/quic-go@v0.44.1-0.20240520163451-20b689a59136/integrationtests/self/benchmark_test.go (about)

     1  package self_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"testing"
     8  
     9  	"github.com/metacubex/quic-go"
    10  )
    11  
    12  func BenchmarkHandshake(b *testing.B) {
    13  	b.ReportAllocs()
    14  
    15  	ln, err := quic.ListenAddr("localhost:0", tlsConfig, nil)
    16  	if err != nil {
    17  		b.Fatal(err)
    18  	}
    19  	defer ln.Close()
    20  
    21  	connChan := make(chan quic.Connection, 1)
    22  	go func() {
    23  		for {
    24  			conn, err := ln.Accept(context.Background())
    25  			if err != nil {
    26  				return
    27  			}
    28  			connChan <- conn
    29  		}
    30  	}()
    31  
    32  	conn, err := net.ListenUDP("udp", nil)
    33  	if err != nil {
    34  		b.Fatal(err)
    35  	}
    36  	defer conn.Close()
    37  	tr := &quic.Transport{Conn: conn}
    38  	defer tr.Close()
    39  
    40  	b.ResetTimer()
    41  	for i := 0; i < b.N; i++ {
    42  		c, err := tr.Dial(context.Background(), ln.Addr(), tlsClientConfig, nil)
    43  		if err != nil {
    44  			b.Fatal(err)
    45  		}
    46  		<-connChan
    47  		c.CloseWithError(0, "")
    48  	}
    49  }
    50  
    51  func BenchmarkStreamChurn(b *testing.B) {
    52  	b.ReportAllocs()
    53  
    54  	ln, err := quic.ListenAddr("localhost:0", tlsConfig, &quic.Config{MaxIncomingStreams: 1e10})
    55  	if err != nil {
    56  		b.Fatal(err)
    57  	}
    58  	defer ln.Close()
    59  
    60  	errChan := make(chan error, 1)
    61  	go func() {
    62  		conn, err := ln.Accept(context.Background())
    63  		if err != nil {
    64  			errChan <- err
    65  			return
    66  		}
    67  		close(errChan)
    68  		for {
    69  			str, err := conn.AcceptStream(context.Background())
    70  			if err != nil {
    71  				return
    72  			}
    73  			str.Close()
    74  		}
    75  	}()
    76  
    77  	c, err := quic.DialAddr(context.Background(), fmt.Sprintf("localhost:%d", ln.Addr().(*net.UDPAddr).Port), tlsClientConfig, nil)
    78  	if err != nil {
    79  		b.Fatal(err)
    80  	}
    81  	if err := <-errChan; err != nil {
    82  		b.Fatal(err)
    83  	}
    84  
    85  	b.ResetTimer()
    86  	for i := 0; i < b.N; i++ {
    87  		str, err := c.OpenStreamSync(context.Background())
    88  		if err != nil {
    89  			b.Fatal(err)
    90  		}
    91  		if err := str.Close(); err != nil {
    92  			b.Fatal(err)
    93  		}
    94  	}
    95  }