github.com/zeebo/mon@v0.0.0-20211012163247-13d39bdb54fa/floathist/serialize_test.go (about) 1 package floathist 2 3 import ( 4 "encoding/hex" 5 "testing" 6 7 "github.com/zeebo/assert" 8 "github.com/zeebo/pcg" 9 ) 10 11 func TestSerialize(t *testing.T) { 12 t.Run("Write", func(t *testing.T) { 13 h := new(Histogram) 14 for i := int64(0); i < 10000; i++ { 15 r := float32(pcg.Uint32n(1000) + 500) 16 h.Observe(r) 17 } 18 19 data := h.Serialize(nil) 20 t.Logf("%d\n%s", len(data), hex.Dump(data)) 21 }) 22 23 t.Run("Load", func(t *testing.T) { 24 h := new(Histogram) 25 for i := int64(0); i < 10000; i++ { 26 r := float32(pcg.Uint32n(1000) + 500) 27 h.Observe(r) 28 } 29 30 h2 := new(Histogram) 31 assert.NoError(t, h2.Load(h.Serialize(nil))) 32 33 assert.Equal(t, h.Total(), h2.Total()) 34 assert.Equal(t, h.Sum(), h2.Sum()) 35 t.Log(h.Average()) 36 t.Log(h2.Average()) 37 }) 38 } 39 40 func BenchmarkSerialize(b *testing.B) { 41 b.Run("Write", func(b *testing.B) { 42 h := new(Histogram) 43 for i := int64(0); i < 100000; i++ { 44 r := pcg.Float32() 45 h.Observe(r) 46 } 47 buf := h.Serialize(nil) 48 49 b.SetBytes(int64(len(buf))) 50 b.ResetTimer() 51 b.ReportAllocs() 52 53 for i := 0; i < b.N; i++ { 54 h.Serialize(buf[:0]) 55 } 56 57 b.ReportMetric(float64(len(buf)), "bytes") 58 }) 59 60 b.Run("Load", func(b *testing.B) { 61 h := new(Histogram) 62 for i := int64(0); i < 100000; i++ { 63 r := pcg.Float32() 64 h.Observe(r) 65 } 66 buf := h.Serialize(nil) 67 68 b.SetBytes(int64(len(buf))) 69 b.ResetTimer() 70 b.ReportAllocs() 71 72 for i := 0; i < b.N; i++ { 73 var h Histogram 74 _ = h.Load(buf) 75 } 76 77 b.ReportMetric(float64(len(buf)), "bytes") 78 }) 79 }