github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/test/alloc_test.go (about)

     1  package main
     2  
     3  import (
     4  	client2 "github.com/nyan233/littlerpc/core/client"
     5  	"github.com/nyan233/littlerpc/core/common/logger"
     6  	server2 "github.com/nyan233/littlerpc/core/server"
     7  	"math/rand"
     8  	"testing"
     9  )
    10  
    11  type BenchAlloc struct{}
    12  
    13  func (b *BenchAlloc) AllocBigBytes(size int) ([]byte, error) {
    14  	tmp := make([]byte, size)
    15  	for i := range tmp {
    16  		tmp[i] = byte(rand.Int31n(255))
    17  	}
    18  	return tmp, nil
    19  }
    20  
    21  func (b *BenchAlloc) AllocLittleNBytesInit(n, size int) ([][]byte, error) {
    22  	nBytes := make([][]byte, n)
    23  	for k := range nBytes {
    24  		nBytes[k] = make([]byte, size)
    25  		for j := range nBytes[k] {
    26  			nBytes[k][j] = byte(rand.Int31n(255))
    27  		}
    28  	}
    29  	return nBytes, nil
    30  }
    31  
    32  func (b *BenchAlloc) AllocLittleNBytesNoInit(n, size int) ([][]byte, error) {
    33  	nBytes := make([][]byte, n)
    34  	for k := range nBytes {
    35  		nBytes[k] = make([]byte, size)
    36  	}
    37  	return nBytes, nil
    38  }
    39  
    40  func BenchmarkClientAlloc(b *testing.B) {
    41  	// 关闭服务器烦人的日志
    42  	logger.SetOpenLogger(false)
    43  	s1 := server2.New(server2.WithAddressServer(":1234"), server2.WithOpenLogger(false))
    44  	err := s1.RegisterClass("", new(BenchAlloc), nil)
    45  	if err != nil {
    46  		b.Fatal(err)
    47  	}
    48  	go s1.Service()
    49  	defer s1.Stop()
    50  	c1, err := client2.New(client2.WithAddress(":1234"))
    51  	if err != nil {
    52  		b.Fatal(err)
    53  	}
    54  	p1 := NewBenchAlloc(c1)
    55  	b.Run("ClientBigAlloc", func(b *testing.B) {
    56  		b.ReportAllocs()
    57  		for i := 0; i < b.N; i++ {
    58  			_, err2 := p1.AllocBigBytes(32768)
    59  			if err2 != nil {
    60  				b.Fatal(err2)
    61  			}
    62  		}
    63  	})
    64  	b.Run("ClientLittleAlloc", func(b *testing.B) {
    65  		b.ReportAllocs()
    66  		for i := 0; i < b.N; i++ {
    67  			_, err2 := p1.AllocLittleNBytesNoInit(10, 128)
    68  			if err2 != nil {
    69  				b.Fatal(err2)
    70  			}
    71  		}
    72  	})
    73  }