github.com/birneee/aes6@v0.0.0-20240131140838-9e8f775f7eae/aes6_benchmark_test.go (about)

     1  package aes6
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"github.com/stretchr/testify/assert"
     8  	"runtime"
     9  	"sync"
    10  	"sync/atomic"
    11  	"testing"
    12  )
    13  
    14  func randomAead(t assert.TestingT, tagSize int) (cipher.AEAD, [12]byte) {
    15  	var key [16]byte
    16  	_, err := rand.Read(key[:])
    17  	assert.NoError(t, err)
    18  	var nonce [12]byte
    19  	_, err = rand.Read(nonce[:])
    20  	assert.NoError(t, err)
    21  	block, err := aes.NewCipher(key[:])
    22  	assert.NoError(t, err)
    23  
    24  	aesgcm, err := NewGCMWithTagSize(block, tagSize)
    25  	assert.NoError(t, err)
    26  	return aesgcm, nonce
    27  }
    28  
    29  func BenchmarkSeal(b *testing.B) {
    30  	aead, nonce := randomAead(b, 6)
    31  	var buf [1516]byte
    32  	sealed := 0
    33  	b.ResetTimer()
    34  	for i := 0; i < b.N; i++ {
    35  		aead.Seal(buf[:], nonce[:], buf[:1500], nil)
    36  		sealed += len(buf)
    37  	}
    38  	b.StopTimer()
    39  
    40  	b.ReportMetric(float64(sealed)/b.Elapsed().Seconds()/1e9, "GB/s")
    41  }
    42  
    43  func BenchmarkOpen(b *testing.B) {
    44  	aead, nonce := randomAead(b, 6)
    45  	var buf [1500]byte
    46  	_, err := rand.Read(buf[:])
    47  	assert.NoError(b, err)
    48  	ciphertext := aead.Seal(nil, nonce[:], buf[:], nil)
    49  	opened := 0
    50  	b.ResetTimer()
    51  	for i := 0; i < b.N; i++ {
    52  		plaintext, err := aead.Open(buf[:], nonce[:], ciphertext, nil)
    53  		assert.NoError(b, err)
    54  		opened += len(plaintext)
    55  	}
    56  	b.StopTimer()
    57  
    58  	b.ReportMetric(float64(opened)/b.Elapsed().Seconds()/1e9, "GB/s")
    59  }
    60  
    61  func BenchmarkOpenParallel(b *testing.B) {
    62  	aead, nonce := randomAead(b, 6)
    63  	var buf [1516]byte
    64  	_, err := rand.Read(buf[:])
    65  	assert.NoError(b, err)
    66  	ciphertext := aead.Seal(nil, nonce[:], buf[:1500], nil)
    67  	totalOpened := atomic.Int64{}
    68  	workers := runtime.NumCPU()
    69  	jobsPerWorker := b.N
    70  	wg := sync.WaitGroup{}
    71  	wg.Add(workers)
    72  	b.ResetTimer()
    73  	for i := 0; i < workers; i++ {
    74  		go func() {
    75  			opened := 0
    76  			for j := 0; j < jobsPerWorker; j++ {
    77  				plaintext, _ := aead.Open(buf[:], nonce[:], ciphertext, nil)
    78  				opened += len(plaintext)
    79  			}
    80  			totalOpened.Add(int64(opened))
    81  			wg.Done()
    82  		}()
    83  	}
    84  	wg.Wait()
    85  	b.StopTimer()
    86  
    87  	b.ReportMetric(float64(totalOpened.Load())/b.Elapsed().Seconds()/1e9, "GB/s")
    88  }