Skip to content

Instantly share code, notes, and snippets.

@mwittig
Last active June 24, 2022 16:09
Show Gist options
  • Save mwittig/f1e6a81c2378906292e2e4961f422870 to your computer and use it in GitHub Desktop.
Save mwittig/f1e6a81c2378906292e2e4961f422870 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"testing"
)
var data []string
func TestMain(m *testing.M) {
os.Exit(initTestSuite(m))
}
func initTestSuite(m *testing.M) int {
const nRecords int = 100000
data = make([]string, nRecords)
record := strings.Repeat("0123456789", 60)
for i := 0; i < nRecords; i++ {
data[i] = record
}
e := m.Run()
return e
}
// fut represents the function under test. It will be tested with different given buffer size. If 0 is passed
// the default buffer size (4K) will be used.
func fut(t *testing.B, bufSize int) {
f, err := os.Create("file.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
w := bufio.NewWriter(f)
if bufSize > 0 {
w = bufio.NewWriterSize(w, bufSize)
}
//t.Logf("Buffer Size %d", w.Size())
for _, d := range data {
_, err := w.WriteString(fmt.Sprint(d + "\n"))
if err != nil {
fmt.Println(err)
}
}
err = w.Flush()
if err != nil {
log.Fatal(err)
}
}
func BenchmarkWrite(b *testing.B) {
tests := []struct {
name string
bufSize int
}{
{
name: "Default Buffer Size",
bufSize: 0,
},
{
name: "Buffer Size 16K",
bufSize: 16384,
},
{
name: "Buffer Size 64K",
bufSize: 65536,
},
}
for _, tc := range tests {
b.Run(tc.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
fut(b, tc.bufSize)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment