Skip to content

Instantly share code, notes, and snippets.

@adoublef
Created October 14, 2024 11:42
Show Gist options
  • Save adoublef/89df6d590ef5be4b0b5d1877c7059b04 to your computer and use it in GitHub Desktop.
Save adoublef/89df6d590ef5be4b0b5d1877c7059b04 to your computer and use it in GitHub Desktop.
package aesctr256hmacsha256_test
import (
"crypto/aes"
"crypto/cipher"
"embed"
"encoding/hex"
"io"
"os"
"testing"
)
//go:embed all:testdata/input/*
var embedFS embed.FS
func Benchmark_aesctr256hmacsha256(b *testing.B) {
b.Run("Copy32", func(b *testing.B) {
// create a temp file
dst, err := os.CreateTemp(b.TempDir(), "sink-*")
if err != nil {
b.Errorf(`dst, %q := os.CreateTemp(b.TempDir(), "sink-*")`, err)
}
// create compression
// create a tar file
b.ResetTimer()
for n := 0; n < b.N; n++ {
b.StopTimer()
src, err := embedFS.Open("testdata/input/hello.txt")
if err != nil {
b.Errorf(`_, %q := embedFS.Open("testdata/input/hello.txt")`, err)
}
var (
buf = make([]byte, 32*1024)
)
b.StartTimer()
_, err = io.CopyBuffer(dst, src, buf)
if err != nil {
b.Errorf(`_, %q := io.Copy(dst, src)`, err)
}
}
})
b.Run("BlockCopy32", func(b *testing.B) {
// create a temp file
dst, err := os.CreateTemp(b.TempDir(), "sink-*")
if err != nil {
b.Errorf(`dst, %q := os.CreateTemp(b.TempDir(), "sink-*")`, err)
}
var (
key, _ = hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
iv [aes.BlockSize]byte
)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
var (
stream = cipher.NewCTR(block, iv[:])
writer = &cipher.StreamWriter{S: stream, W: dst}
)
// create compression
// create a tar file
b.ResetTimer()
for n := 0; n < b.N; n++ {
b.StopTimer()
src, err := embedFS.Open("testdata/input/hello.txt")
if err != nil {
b.Errorf(`_, %q := embedFS.Open("testdata/input/hello.txt")`, err)
}
var (
// block+hmac
buf = make([]byte, 32*1024)
)
b.StartTimer()
benchCopy(b, writer, src, buf)
}
})
}
func benchCopy(b *testing.B, dst io.Writer, src io.Reader, buf []byte) {
_, err := io.CopyBuffer(dst, src, buf)
if err != nil {
b.Errorf(`_, %q := io.Copy(dst, src)`, err)
}
}
@adoublef
Copy link
Author

results

goos: darwin
goarch: arm64
pkg: go.bench/crypto/aesctr256hmacsha256
cpu: Apple M2
Benchmark_aesctr256hmacsha256/Copy32                1000              7347 ns/op           32776 B/op          2 allocs/op
Benchmark_aesctr256hmacsha256/BlockCopy32           1000              4875 ns/op              16 B/op          1 allocs/op

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