github.com/stellar/go-xdr@v0.0.0-20231122183749-b53fb00bcac2/xdr2/bench_test.go (about) 1 /* 2 * Copyright (c) 2012-2014 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 "bytes" 21 "testing" 22 "unsafe" 23 24 xdr "github.com/stellar/go-xdr/xdr2" 25 ) 26 27 // BenchmarkUnmarshal benchmarks the Unmarshal function by using a dummy 28 // ImageHeader structure. 29 func BenchmarkUnmarshal(b *testing.B) { 30 b.StopTimer() 31 // Hypothetical image header format. 32 type ImageHeader struct { 33 Signature [3]byte 34 Version uint32 35 IsGrayscale bool 36 NumSections uint32 37 } 38 // XDR encoded data described by the above structure. 39 encodedData := []byte{ 40 0xAB, 0xCD, 0xEF, 0x00, 41 0x00, 0x00, 0x00, 0x02, 42 0x00, 0x00, 0x00, 0x01, 43 0x00, 0x00, 0x00, 0x0A, 44 } 45 var h ImageHeader 46 b.StartTimer() 47 48 for i := 0; i < b.N; i++ { 49 r := bytes.NewReader(encodedData) 50 _, _ = xdr.Unmarshal(r, &h) 51 } 52 b.SetBytes(int64(len(encodedData))) 53 } 54 55 // BenchmarkMarshal benchmarks the Marshal function by using a dummy ImageHeader 56 // structure. 57 func BenchmarkMarshal(b *testing.B) { 58 b.StopTimer() 59 // Hypothetical image header format. 60 type ImageHeader struct { 61 Signature [3]byte 62 Version uint32 63 IsGrayscale bool 64 NumSections uint32 65 } 66 h := ImageHeader{[3]byte{0xAB, 0xCD, 0xEF}, 2, true, 10} 67 size := unsafe.Sizeof(h) 68 w := bytes.NewBuffer(nil) 69 b.StartTimer() 70 71 for i := 0; i < b.N; i++ { 72 w.Reset() 73 _, _ = xdr.Marshal(w, &h) 74 } 75 b.SetBytes(int64(size)) 76 }