github.com/stellar/go-xdr@v0.0.0-20231122183749-b53fb00bcac2/xdr/bench_test.go (about)

     1  /*
     2   * Copyright (c) 2012 Dave Collins <dave@davec.name>
     3   *
     4   * Permission to use, copy, modify, and distribute this software for any
     5   * purpose with or without fee is hereby granted, provided that the above
     6   * copyright notice and this permission notice appear in all copies.
     7   *
     8   * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     9   * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    10   * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    11   * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    12   * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    13   * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    14   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    15   */
    16  
    17  package xdr_test
    18  
    19  import (
    20  	"testing"
    21  	"unsafe"
    22  
    23  	"github.com/stellar/go-xdr/xdr"
    24  )
    25  
    26  func BenchmarkUnmarshal(b *testing.B) {
    27  	b.StopTimer()
    28  	// Hypothetical image header format.
    29  	type ImageHeader struct {
    30  		Signature   [3]byte
    31  		Version     uint32
    32  		IsGrayscale bool
    33  		NumSections uint32
    34  	}
    35  	// XDR encoded data described by the above structure.
    36  	encodedData := []byte{
    37  		0xAB, 0xCD, 0xEF, 0x00,
    38  		0x00, 0x00, 0x00, 0x02,
    39  		0x00, 0x00, 0x00, 0x01,
    40  		0x00, 0x00, 0x00, 0x0A}
    41  	var h ImageHeader
    42  	b.StartTimer()
    43  	for i := 0; i < b.N; i++ {
    44  		_, _ = xdr.Unmarshal(encodedData, &h)
    45  	}
    46  	b.SetBytes(int64(len(encodedData)))
    47  }
    48  
    49  func BenchmarkMarshal(b *testing.B) {
    50  	b.StopTimer()
    51  	// Hypothetical image header format.
    52  	type ImageHeader struct {
    53  		Signature   [3]byte
    54  		Version     uint32
    55  		IsGrayscale bool
    56  		NumSections uint32
    57  	}
    58  	h := ImageHeader{[3]byte{0xAB, 0xCD, 0xEF}, 2, true, 10}
    59  	size := unsafe.Sizeof(h)
    60  	b.StartTimer()
    61  	for i := 0; i < b.N; i++ {
    62  		_, _ = xdr.Marshal(&h)
    63  	}
    64  	b.SetBytes(int64(size))
    65  }