Skip to content

Instantly share code, notes, and snippets.

@mroth
Last active June 30, 2023 17:24
Show Gist options
  • Save mroth/b98a43537f40e8cd47384fb95d6c1bde to your computer and use it in GitHub Desktop.
Save mroth/b98a43537f40e8cd47384fb95d6c1bde to your computer and use it in GitHub Desktop.
buffered randomness throughput benchmarks
package main
import (
"bufio"
"crypto/rand"
"strconv"
"testing"
)
func BenchmarkRandReads(b *testing.B) {
const size = 16 // assume we need 16 bytes of entropy per seed operation
var dst [size]byte
b.Run("normal", func(b *testing.B) {
b.SetBytes(size)
for i := 0; i < b.N; i++ {
_, _ = rand.Read(dst[:])
}
})
b.Run("buffered", func(b *testing.B) {
bufSizes := []int{128, 256, 512, 1024, 2048, 4096}
for _, bs := range bufSizes {
b.Run(strconv.Itoa(bs), func(b *testing.B) {
b.SetBytes(size)
bufReader := bufio.NewReaderSize(rand.Reader, bs)
for i := 0; i < b.N; i++ {
_, _ = bufReader.Read(dst[:])
}
})
}
})
}
@mroth
Copy link
Author

mroth commented Jun 30, 2023

Results on laptop:

$ go test -bench=. -cpu=1
goos: darwin
goarch: arm64

BenchmarkRandReads/normal                2845966               403.4 ns/op        39.67 MB/s
BenchmarkRandReads/buffered/128         22289520                54.02 ns/op      296.17 MB/s
BenchmarkRandReads/buffered/256         38142613                31.10 ns/op      514.41 MB/s
BenchmarkRandReads/buffered/512         38099823                30.96 ns/op      516.72 MB/s
BenchmarkRandReads/buffered/1024        39591655                30.47 ns/op      525.09 MB/s
BenchmarkRandReads/buffered/2048        38853812                30.29 ns/op      528.30 MB/s
BenchmarkRandReads/buffered/4096        39630936                30.11 ns/op      531.43 MB/s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment