github.com/niubaoshu/gotiny@v0.0.4-0.20211018120156-10d393f19ad0/profile/a_bench_test.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "math/rand" 6 "testing" 7 "time" 8 9 "github.com/niubaoshu/gotiny" 10 ) 11 12 type A struct { 13 Name string 14 BirthDay time.Time 15 Phone string 16 Siblings int 17 Spouse bool 18 Money float64 19 } 20 21 func BenchmarkGotinyMarshal(b *testing.B) { 22 b.StopTimer() 23 data := generate() 24 b.ReportAllocs() 25 e := gotiny.NewEncoder(A{}) 26 b.StartTimer() 27 for i := 0; i < b.N; i++ { 28 e.Encode(data[rand.Intn(len(data))]) 29 } 30 } 31 32 func generate() []*A { 33 a := make([]*A, 0, 1000) 34 for i := 0; i < 1000; i++ { 35 a = append(a, &A{ 36 Name: randString(16), 37 BirthDay: time.Now(), 38 Phone: randString(10), 39 Siblings: rand.Intn(5), 40 Spouse: rand.Intn(2) == 1, 41 Money: rand.Float64(), 42 }) 43 } 44 return a 45 } 46 47 func randString(l int) string { 48 buf := make([]byte, l) 49 for i := 0; i < (l+1)/2; i++ { 50 buf[i] = byte(rand.Intn(256)) 51 } 52 return fmt.Sprintf("%x", buf)[:l] 53 }