github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/common/msgparser/bench_test.go (about)

     1  package msgparser
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/nyan233/littlerpc/core/container"
     6  	message2 "github.com/nyan233/littlerpc/core/protocol/message"
     7  	"github.com/nyan233/littlerpc/core/protocol/message/gen"
     8  	"io"
     9  	"testing"
    10  )
    11  
    12  func BenchmarkParser(b *testing.B) {
    13  	const (
    14  		UsageParseOnReader = true
    15  	)
    16  	parser := Get(DefaultParser)(NewDefaultSimpleAllocTor(), MaxBufferSize*32)
    17  	for i := 1; i <= (1 << 10); i *= 4 {
    18  		b.Run(fmt.Sprintf("LRPCProtocol-OneParse-%dMessage", i), func(b *testing.B) {
    19  			b.StopTimer()
    20  			var runCount int
    21  			parser.Reset()
    22  			messages := make([]byte, 0, i*64)
    23  			messageSplits := make([]*message2.Message, 0)
    24  			lengths := make([]int, 0)
    25  			for j := 0; j < i; j++ {
    26  				msg := gen.NoMux(gen.Little)
    27  				messageSplits = append(messageSplits, msg)
    28  				var bytes container.Slice[byte]
    29  				err := message2.Marshal(msg, &bytes)
    30  				if err != nil {
    31  					b.Fatal(err)
    32  				}
    33  				lengths = append(lengths, bytes.Len())
    34  				messages = append(messages, bytes...)
    35  			}
    36  			var point int
    37  			for index, length := range lengths {
    38  				msg := message2.New()
    39  				err := message2.Unmarshal(messages[point:point+length], msg)
    40  				if err != nil {
    41  					var bytes container.Slice[byte]
    42  					err = message2.Marshal(messageSplits[index], &bytes)
    43  					b.Fatal(index, length, err)
    44  				}
    45  				point += length
    46  			}
    47  			buf2 := make([]byte, len(messages))
    48  			b.StartTimer()
    49  			b.ReportAllocs()
    50  			for j := 0; j < b.N; j++ {
    51  				var parseMsgs []ParserMessage
    52  				var err error
    53  				if UsageParseOnReader {
    54  					parseMsgs, err = parser.ParseOnReader(func(bytes []byte) (n int, err error) {
    55  						return copy(bytes, messages), io.EOF
    56  					})
    57  				} else {
    58  					// 模拟网络框架的拷贝
    59  					copy(buf2, messages)
    60  					parseMsgs, err = parser.Parse(buf2)
    61  				}
    62  				if err != nil {
    63  					_, err = parser.Parse(messages)
    64  					b.Fatal(j, err)
    65  				}
    66  				b.StopTimer()
    67  				for _, v := range parseMsgs {
    68  					parser.Free(v.Message)
    69  				}
    70  				b.StartTimer()
    71  				b.SetBytes(int64(len(messages)))
    72  				runCount++
    73  			}
    74  			b.ReportMetric(float64(runCount), "RunCount")
    75  		})
    76  	}
    77  }