Debian Codegraph @

codec/bench/bench_test.go

raw symbols SCIP
1 // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
2 // Use of this source code is governed by a MIT license found in the LICENSE file.
3
4 package codec
5
6 // bench_test is the "helper" file for all benchmarking tests.
7 //
8 // There are also benchmarks which depend on just codec and the stdlib,
9 // and benchmarks which depend on external libraries.
10 // It is an explicit goal that you can run benchmarks without external
11 // dependencies (which is why the 'x' build tag was explicitly introduced).
12 //
13 // There are 2 ways of running tests:
14 // - generated
15 // - not generated
16 //
17 // Consequently, we have 4 groups:
18 // - codec_bench (gen, !gen)
19 // - stdlib_bench (!gen only)
20 // - x_bench (!gen only)
21 // - x_bench_gen (gen only)
22 //
23 // We also have 4 matching suite files.
24 // - z_all_bench (rename later to z_all_codec_bench???)
25 // - z_all_stdlib_bench
26 // - z_all_x_bench
27 // - z_all_x_bench_gen
28 //
29 // Finally, we have a single test (TestBenchInit) that
30 // will log information about whether each format can
31 // encode or not, how long to encode (unscientifically),
32 // and the encode size.
33 //
34 // This test MUST be run always, as it calls init() internally
35
36 import (
37 "reflect"
38 "runtime"
39 "testing"
40 "time"
41 )
42
43 // Sample way to run:
44 // go test -bi -bv -bd=1 -benchmem -bench=.
45
46 const (
47 benchUnscientificRes = true
48 benchVerify = true
49 benchRecover = true
50 benchShowJsonOnError = true
51 )
52
53 var (
54 benchTs *TestStruc
55 approxSize int
56 benchCheckers []benchChecker
57 )
58
59 type benchEncFn func(interface{}, []byte) ([]byte, error)
60 type benchDecFn func([]byte, interface{}) error
61 type benchIntfFn func() interface{}
62
63 type benchChecker struct {
64 name string
65 encodefn benchEncFn
66 decodefn benchDecFn
67 }
68
69 func init() {
70 testPreInitFns = append(testPreInitFns, benchPreInit)
71 // testPostInitFns = append(testPostInitFns, codecbenchPostInit)
72 }
73
74 func benchPreInit() {
75 benchTs = newTestStruc(testDepth, testNumRepeatString, true, !testSkipIntf, testMapStringKeyOnly)
76 approxSize = approxDataSize(reflect.ValueOf(benchTs)) * 2 // multiply by 1.5 or 2 to appease msgp, and prevent alloc
77 // bytesLen := 1024 * 4 * (testDepth + 1) * (testDepth + 1)
78 // if bytesLen < approxSize {
79 // bytesLen = approxSize
80 // }
81
82 if !testBenchmarkNoConfig {
83 // benchmark comparisons use zerocopy (easyjson, json-iterator, etc).
84 // use zerocopy for the benchmarks, for best performance, and better comparison to others.
85 testJsonH.ZeroCopy = true
86 testCborH.ZeroCopy = true
87 testMsgpackH.ZeroCopy = true
88 testSimpleH.ZeroCopy = true
89 testBincH.ZeroCopy = true
90
91 // std-lib encoging/json does the following, which we will do for codec in these benchmarks.
92 // - sets into a map without getting what's there first.
93 // - sets into an interface value regardless of what was in there
94 // - sets slice to zero len first, then appends (equivalent to ignoring slice contents)
95
96 testJsonH.MapValueReset = true
97 testJsonH.InterfaceReset = true
98 testJsonH.SliceElementReset = true
99 }
100 }
101
102 func benchReinit() {
103 benchCheckers = nil
104 }
105
106 func benchmarkDivider() {
107 // logTv(nil, "-------------------------------\n")
108 println()
109 }
110
111 // func Test0(t *testing.T) {
112 // testOnce.Do(testInitAll)
113 // }
114
115 func TestBenchInit(t *testing.T) {
116 testOnce.Do(testInitAll)
117 if !testing.Verbose() {
118 return
119 }
120 // t.Logf("..............................................")
121 t.Logf("BENCHMARK INIT: %v", time.Now())
122 // t.Logf("To run full benchmark comparing encodings, use: \"go test -bench=.\"")
123 t.Logf("Benchmark: ")
124 t.Logf("\tStruct recursive Depth: %d", testDepth)
125 if approxSize > 0 {
126 t.Logf("\tApproxDeepSize Of benchmark Struct: %d bytes", approxSize)
127 }
128 if benchUnscientificRes {
129 t.Logf("Benchmark One-Pass Run (with Unscientific Encode/Decode times): ")
130 } else {
131 t.Logf("Benchmark One-Pass Run:")
132 }
133 for _, bc := range benchCheckers {
134 doBenchCheck(t, bc.name, bc.encodefn, bc.decodefn)
135 }
136 if testVerbose {
137 t.Logf("..............................................")
138 t.Logf("<<<<====>>>> depth: %v, ts: %#v\n", testDepth, benchTs)
139 }
140 runtime.GC()
141 time.Sleep(100 * time.Millisecond)
142 }
143
144 var vBenchTs = TestStruc{}
145
146 func fnBenchNewTs() interface{} {
147 vBenchTs = TestStruc{}
148 return &vBenchTs
149 // return new(TestStruc)
150 }
151
152 // const benchCheckDoDeepEqual = false
153
154 func benchRecoverPanic(t *testing.B) {
155 if benchRecover {
156 if r := recover(); r != nil {
157 t.Logf("(recovered) panic: %v\n", r)
158 t.FailNow()
159 }
160 }
161 }
162
163 func benchRecoverPanicT(t *testing.T) {
164 if benchRecover {
165 if r := recover(); r != nil {
166 t.Logf("(recovered) panic: %v\n", r)
167 t.FailNow()
168 }
169 }
170 }
171
172 func doBenchCheck(t *testing.T, name string, encfn benchEncFn, decfn benchDecFn) {
173 // if benchUnscientificRes {
174 // t.Logf("-------------- %s ----------------", name)
175 // }
176 defer benchRecoverPanicT(t)
177 runtime.GC()
178 tnow := time.Now()
179 buf, err := encfn(benchTs, nil)
180 if err != nil {
181 t.Logf("\t%10s: **** Error encoding benchTs: %v", name, err)
182 return
183 }
184 encDur := time.Since(tnow)
185 encLen := len(buf)
186 runtime.GC()
187 if !benchUnscientificRes {
188 t.Logf("\t%10s: len: %d bytes\n", name, encLen)
189 return
190 }
191 tnow = time.Now()
192 var ts2 TestStruc
193 if err = decfn(buf, &ts2); err != nil {
194 t.Logf("\t%10s: **** Error decoding into new TestStruc: %v", name, err)
195 return
196 }
197 decDur := time.Since(tnow)
198 // if benchCheckDoDeepEqual {
199 if benchVerify {
200 err = deepEqual(benchTs, &ts2)
201 if err == nil {
202 t.Logf("\t%10s: len: %d bytes,\t encode: %v,\t decode: %v,\tencoded == decoded", name, encLen, encDur, decDur)
203 } else {
204 t.Logf("\t%10s: len: %d bytes,\t encode: %v,\t decode: %v,\tencoded != decoded: %v", name, encLen, encDur, decDur, err)
205 }
206 } else {
207 t.Logf("\t%10s: len: %d bytes,\t encode: %v,\t decode: %v", name, encLen, encDur, decDur)
208 }
209 return
210 }
211
212 func fnBenchmarkEncode(b *testing.B, encName string, ts interface{}, encfn benchEncFn) {
213 defer benchRecoverPanic(b)
214 testOnce.Do(testInitAll)
215 // ignore method params: ts, and work on benchTs directly
216 ts = benchTs
217 var err error
218 bs := make([]byte, 0, approxSize)
219
220 // do initial warm up by running encode one time
221 if bs, err = encfn(ts, bs); err != nil {
222 b.Logf("Error encoding benchTs: %s: %v", encName, err)
223 b.FailNow()
224 }
225
226 runtime.GC()
227 b.ResetTimer()
228 for i := 0; i < b.N; i++ {
229 if _, err = encfn(ts, bs); err != nil {
230 b.Logf("Error encoding benchTs: %s: %v", encName, err)
231 b.FailNow()
232 }
233 }
234 }
235
236 func fnBenchmarkDecode(b *testing.B, encName string, ts interface{},
237 encfn benchEncFn, decfn benchDecFn, newfn benchIntfFn,
238 ) {
239 defer benchRecoverPanic(b)
240 testOnce.Do(testInitAll)
241 // ignore method params: ts and newfn, and work on benchTs and TestStruc directly
242 ts = benchTs
243
244 buf := make([]byte, 0, approxSize)
245 buf, err := encfn(ts, buf)
246 if err != nil {
247 b.Logf("Error encoding benchTs: %s: %v", encName, err)
248 b.FailNow()
249 }
250
251 // do initial warm up by running decode one time
252 locTs := new(TestStruc)
253 ts = locTs
254 // ts = newfn()
255 if err = decfn(buf, ts); err != nil {
256 b.Logf("Error decoding into new TestStruc: %s: %v", encName, err)
257 b.FailNow()
258 }
259
260 // if false && benchVerify { // do not do benchVerify during decode
261 // // ts2 := newfn()
262 // ts1 := ts.(*TestStruc)
263 // ts2 := new(TestStruc)
264 // if err = decfn(buf, ts2); err != nil {
265 // failT(b, "BenchVerify: Error decoding benchTs: %s: %v", encName, err)
266 // }
267 // if err = deepEqual(ts1, ts2); err != nil {
268 // failT(b, "BenchVerify: Error comparing benchTs: %s: %v", encName, err)
269 // }
270 // }
271
272 runtime.GC()
273 b.ResetTimer()
274 for i := 0; i < b.N; i++ {
275 *locTs = TestStruc{}
276 // ts = newfn()
277 if err = decfn(buf, ts); err != nil {
278 b.Logf("Error decoding into new TestStruc: %s: %v", encName, err)
279 b.FailNow()
280 }
281 }
282 }