github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/iavl/benchmarks/hash_test.go (about)

     1  package benchmarks
     2  
     3  import (
     4  	"crypto"
     5  	"fmt"
     6  	"hash"
     7  	"testing"
     8  
     9  	_ "crypto/sha256"
    10  
    11  	_ "golang.org/x/crypto/ripemd160"
    12  	_ "golang.org/x/crypto/sha3"
    13  )
    14  
    15  func BenchmarkHash(b *testing.B) {
    16  	hashers := []struct {
    17  		name   string
    18  		size   int
    19  		hasher hash.Hash
    20  	}{
    21  		{"ripemd160", 64, crypto.RIPEMD160.New()},
    22  		{"ripemd160", 512, crypto.RIPEMD160.New()},
    23  		{"sha2-256", 64, crypto.SHA256.New()},
    24  		{"sha2-256", 512, crypto.SHA256.New()},
    25  		{"sha3-256", 64, crypto.SHA3_256.New()},
    26  		{"sha3-256", 512, crypto.SHA3_256.New()},
    27  	}
    28  
    29  	for _, h := range hashers {
    30  		prefix := fmt.Sprintf("%s-%d", h.name, h.size)
    31  		b.Run(prefix, func(sub *testing.B) {
    32  			benchHasher(sub, h.hasher, h.size)
    33  		})
    34  	}
    35  }
    36  
    37  func benchHasher(b *testing.B, hasher hash.Hash, size int) {
    38  	b.Helper()
    39  
    40  	// create all random bytes before to avoid timing this
    41  	inputs := randBytes(b.N + size + 1)
    42  
    43  	for i := 0; i < b.N; i++ {
    44  		hasher.Reset()
    45  		// grab a slice of size bytes from random string
    46  		hasher.Write(inputs[i : i+size])
    47  		hasher.Sum(nil)
    48  	}
    49  }