github.com/scottcagno/storage@v1.8.0/pkg/bw/writer_test.go (about) 1 package bw 2 3 import ( 4 "bufio" 5 "bytes" 6 "fmt" 7 "github.com/scottcagno/storage/pkg/util" 8 "testing" 9 ) 10 11 var result interface{} 12 13 func BenchmarkNewWriter_WriteV1(b *testing.B) { 14 15 var bb bytes.Buffer 16 bb.Grow(4096) 17 w := NewWriter(&bb) 18 var x int 19 var err error 20 21 b.ReportAllocs() 22 b.ResetTimer() 23 for n := 0; n < b.N; n++ { 24 x, err = w.Write(util.RandBytes(512)) 25 if err != nil { 26 b.Error(err) 27 } 28 err = w.Flush() 29 if err != nil { 30 b.Error(err) 31 } 32 } 33 // always store the result to a package level variable 34 // so the compiler cannot eliminate the Benchmark itself. 35 result = x 36 } 37 38 func BenchmarkNewWriter_WriteV2(b *testing.B) { 39 40 var bb bytes.Buffer 41 bb.Grow(4096) 42 w := bufio.NewWriterSize(&bb, defaultBufSize) 43 var x int 44 var err error 45 46 b.ReportAllocs() 47 b.ResetTimer() 48 for n := 0; n < b.N; n++ { 49 x, err = w.Write(util.RandBytes(512)) 50 if err != nil { 51 b.Error(err) 52 } 53 err = w.Flush() 54 if err != nil { 55 b.Error(err) 56 } 57 } 58 // always store the result to a package level variable 59 // so the compiler cannot eliminate the Benchmark itself. 60 result = x 61 } 62 63 func TestNewWriter_WriteV1(t *testing.T) { 64 65 var bb bytes.Buffer 66 w := NewWriterSize(&bb, 256, 64) 67 68 n, err := w.Write([]byte("this is a test, this is only a test. let's see if this ends up working or not.... hmmm")) 69 if err != nil { 70 t.Error(err) 71 } 72 err = w.Flush() 73 if err != nil { 74 t.Error(err) 75 } 76 fmt.Printf("off=%d, data=%q (len=%d)\n", n, bb.Bytes(), len(bb.Bytes())) 77 78 n, err = w.Write([]byte("and this is another test.")) 79 if err != nil { 80 t.Error(err) 81 } 82 err = w.Flush() 83 if err != nil { 84 t.Error(err) 85 } 86 fmt.Printf("off=%d, data=%q (len=%d)\n", n, bb.Bytes(), len(bb.Bytes())) 87 }