summaryrefslogtreecommitdiffstats
path: root/xdr/bench_test.go
blob: 26dcb29e5422517a61260afd4151667b48653d49 (plain)
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
// Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file.

package xdr_test

import (
	"io"
	"io/ioutil"
	"testing"
)

type XDRBenchStruct struct {
	I1  uint64
	I2  uint32
	I3  uint16
	Bs0 []byte // max:128
	Bs1 []byte
	S0  string // max:128
	S1  string
}

var res []byte // no to be optimized away
var s = XDRBenchStruct{
	I1:  42,
	I2:  43,
	I3:  44,
	Bs0: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
	Bs1: []byte{11, 12, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
	S0:  "Hello World! String one.",
	S1:  "Hello World! String two.",
}
var e = s.MarshalXDR()

func BenchmarkThisMarshal(b *testing.B) {
	for i := 0; i < b.N; i++ {
		res = s.MarshalXDR()
	}
}

func BenchmarkThisUnmarshal(b *testing.B) {
	var t XDRBenchStruct
	for i := 0; i < b.N; i++ {
		err := t.UnmarshalXDR(e)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkThisEncode(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_, err := s.EncodeXDR(ioutil.Discard)
		if err != nil {
			b.Fatal(err)
		}
	}
}

type repeatReader struct {
	data []byte
}

func (r *repeatReader) Read(bs []byte) (n int, err error) {
	if len(bs) > len(r.data) {
		err = io.EOF
	}
	n = copy(bs, r.data)
	r.data = r.data[n:]
	return n, err
}

func (r *repeatReader) Reset(bs []byte) {
	r.data = bs
}

func BenchmarkThisDecode(b *testing.B) {
	rr := &repeatReader{e}
	var t XDRBenchStruct
	for i := 0; i < b.N; i++ {
		err := t.DecodeXDR(rr)
		if err != nil {
			b.Fatal(err)
		}
		rr.Reset(e)
	}
}