Skip to content

Instantly share code, notes, and snippets.

@mroth
Created June 4, 2024 21:44
Show Gist options
  • Save mroth/2bff3a007c174630dc6aa9aafbcbe3b3 to your computer and use it in GitHub Desktop.
Save mroth/2bff3a007c174630dc6aa9aafbcbe3b3 to your computer and use it in GitHub Desktop.
buffered randomness throughput benchmarks
package main
import (
"bufio"
"crypto/rand"
"fmt"
"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("buffer=none", func(b *testing.B) {
b.SetBytes(size)
for i := 0; i < b.N; i++ {
_, _ = rand.Read(dst[:])
}
})
bufSizes := []int{128, 256, 512, 1024, 2048, 4096}
for _, bs := range bufSizes {
b.Run(fmt.Sprintf("buffer=%d", bs), func(b *testing.B) {
b.SetBytes(size)
bufReader := bufio.NewReaderSize(rand.Reader, bs)
for i := 0; i < b.N; i++ {
_, _ = bufReader.Read(dst[:])
}
})
}
}
BenchmarkRandReads/buffer=none 2859973 411.0 ns/op 38.93 MB/s
BenchmarkRandReads/buffer=128 22197540 54.26 ns/op 294.90 MB/s
BenchmarkRandReads/buffer=256 37927024 31.17 ns/op 513.39 MB/s
BenchmarkRandReads/buffer=512 38238277 31.08 ns/op 514.84 MB/s
BenchmarkRandReads/buffer=1024 37930171 30.64 ns/op 522.23 MB/s
BenchmarkRandReads/buffer=2048 38966889 30.62 ns/op 522.45 MB/s
BenchmarkRandReads/buffer=4096 39039996 30.33 ns/op 527.45 MB/s
@mroth
Copy link
Author

mroth commented Jun 4, 2024

all buffering was removed from crypto/rand in https://go-review.googlesource.com/c/go/+/390038, however it appears to add significant benefit to throughput when doing many small sequential reads.

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