summaryrefslogtreecommitdiff
path: root/src/pkg/encoding/gob/timing_test.go
blob: 13eb11925352894f427ab76d886f6ef12461767d (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
88
89
90
91
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gob

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"testing"
)

type Bench struct {
	A int
	B float64
	C string
	D []byte
}

func benchmarkEndToEnd(r io.Reader, w io.Writer, b *testing.B) {
	b.StopTimer()
	enc := NewEncoder(w)
	dec := NewDecoder(r)
	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		if enc.Encode(bench) != nil {
			panic("encode error")
		}
		if dec.Decode(bench) != nil {
			panic("decode error")
		}
	}
}

func BenchmarkEndToEndPipe(b *testing.B) {
	r, w, err := os.Pipe()
	if err != nil {
		b.Fatal("can't get pipe:", err)
	}
	benchmarkEndToEnd(r, w, b)
}

func BenchmarkEndToEndByteBuffer(b *testing.B) {
	var buf bytes.Buffer
	benchmarkEndToEnd(&buf, &buf, b)
}

func TestCountEncodeMallocs(t *testing.T) {
	const N = 1000

	var buf bytes.Buffer
	enc := NewEncoder(&buf)
	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}

	allocs := testing.AllocsPerRun(N, func() {
		err := enc.Encode(bench)
		if err != nil {
			t.Fatal("encode:", err)
		}
	})
	fmt.Printf("mallocs per encode of type Bench: %v\n", allocs)
}

func TestCountDecodeMallocs(t *testing.T) {
	const N = 1000

	var buf bytes.Buffer
	enc := NewEncoder(&buf)
	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}

	// Fill the buffer with enough to decode
	testing.AllocsPerRun(N, func() {
		err := enc.Encode(bench)
		if err != nil {
			t.Fatal("encode:", err)
		}
	})

	dec := NewDecoder(&buf)
	allocs := testing.AllocsPerRun(N, func() {
		*bench = Bench{}
		err := dec.Decode(&bench)
		if err != nil {
			t.Fatal("decode:", err)
		}
	})
	fmt.Printf("mallocs per decode of type Bench: %v\n", allocs)
}