github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/encoding/gob/timing_test.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gob
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"os"
    12  	"runtime"
    13  	"testing"
    14  )
    15  
    16  type Bench struct {
    17  	A int
    18  	B float64
    19  	C string
    20  	D []byte
    21  }
    22  
    23  func benchmarkEndToEnd(r io.Reader, w io.Writer, b *testing.B) {
    24  	b.StopTimer()
    25  	enc := NewEncoder(w)
    26  	dec := NewDecoder(r)
    27  	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}
    28  	b.StartTimer()
    29  	for i := 0; i < b.N; i++ {
    30  		if enc.Encode(bench) != nil {
    31  			panic("encode error")
    32  		}
    33  		if dec.Decode(bench) != nil {
    34  			panic("decode error")
    35  		}
    36  	}
    37  }
    38  
    39  func BenchmarkEndToEndPipe(b *testing.B) {
    40  	r, w, err := os.Pipe()
    41  	if err != nil {
    42  		b.Fatal("can't get pipe:", err)
    43  	}
    44  	benchmarkEndToEnd(r, w, b)
    45  }
    46  
    47  func BenchmarkEndToEndByteBuffer(b *testing.B) {
    48  	var buf bytes.Buffer
    49  	benchmarkEndToEnd(&buf, &buf, b)
    50  }
    51  
    52  func TestCountEncodeMallocs(t *testing.T) {
    53  	if runtime.GOMAXPROCS(0) > 1 {
    54  		t.Skip("skipping; GOMAXPROCS>1")
    55  	}
    56  
    57  	const N = 1000
    58  
    59  	var buf bytes.Buffer
    60  	enc := NewEncoder(&buf)
    61  	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}
    62  
    63  	allocs := testing.AllocsPerRun(N, func() {
    64  		err := enc.Encode(bench)
    65  		if err != nil {
    66  			t.Fatal("encode:", err)
    67  		}
    68  	})
    69  	fmt.Printf("mallocs per encode of type Bench: %v\n", allocs)
    70  }
    71  
    72  func TestCountDecodeMallocs(t *testing.T) {
    73  	if runtime.GOMAXPROCS(0) > 1 {
    74  		t.Skip("skipping; GOMAXPROCS>1")
    75  	}
    76  
    77  	const N = 1000
    78  
    79  	var buf bytes.Buffer
    80  	enc := NewEncoder(&buf)
    81  	bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")}
    82  
    83  	// Fill the buffer with enough to decode
    84  	testing.AllocsPerRun(N, func() {
    85  		err := enc.Encode(bench)
    86  		if err != nil {
    87  			t.Fatal("encode:", err)
    88  		}
    89  	})
    90  
    91  	dec := NewDecoder(&buf)
    92  	allocs := testing.AllocsPerRun(N, func() {
    93  		*bench = Bench{}
    94  		err := dec.Decode(&bench)
    95  		if err != nil {
    96  			t.Fatal("decode:", err)
    97  		}
    98  	})
    99  	fmt.Printf("mallocs per decode of type Bench: %v\n", allocs)
   100  }