forked from alecthomas/go_serialization_benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
90 lines (82 loc) · 2.03 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package goserbench
import (
"fmt"
"math/rand"
"reflect"
"testing"
)
const num = 1000
var comparer = NewComparer()
func init() {
comparer.Add(reflect.TypeOf((*ProtoBufA)(nil)).Elem(), func(i interface{}, i2 interface{}) bool {
ia := i.(ProtoBufA)
ib := i2.(ProtoBufA)
return *ia.BirthDay == *ib.BirthDay && *ia.Name == *ib.Name && *ia.Phone == *ib.Phone && *ia.Money == *ib.Money && *ia.Siblings == *ib.Siblings
})
}
func randString(l int) string {
buf := make([]byte, l)
for i := 0; i < (l+1)/2; i++ {
buf[i] = byte(rand.Intn(256))
}
return fmt.Sprintf("%x", buf)[:l]
}
func generate(new func() interface{}, num int) []interface{} {
a := make([]interface{}, num)
for i := 0; i < num; i++ {
a[i] = new()
}
return a
}
func bench(s Serializer, randNew func() interface{}, validate bool) *serializeBenchResault {
ret := &serializeBenchResault{
serializer: s,
}
data := generate(randNew, num)
ser := make([][]byte, num)
var sumlen int
for i, d := range data {
var buf []byte
buf, ret.merr = s.Marshal(d)
if validate && ret.merr != nil {
return ret
}
t := make([]byte, len(buf))
sumlen += len(buf)
copy(t, buf)
ser[i] = t
}
ret.length = sumlen / num
ret.marshalResult = testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
s.Marshal(data[i%num])
}
})
g := randNew()
ret.unmarshalResult = testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
err := s.Unmarshal(ser[i%num], g)
if err != nil && ret.unmerr == nil {
ret.unmerr = fmt.Errorf("%s failed to unmarshal: %s", s, err.Error())
return
}
if validate {
e := data[i%num]
if !comparer.DeepEqual(e, g) && ret.unmerr == nil {
e, g := indirect(e), indirect(g)
ret.unmerr = fmt.Errorf("\n exp type = %T; value = %+v;\n got type = %T; value = %+v; \n", e, e, g, g)
b.StartTimer()
return
}
}
}
})
return ret
}
func indirect(i interface{}) interface{} {
v := reflect.ValueOf(i)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
return v.Interface()
}