|
| 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 | + // create all random bytes before to avoid timing this |
| 39 | + inputs := randBytes(b.N + size + 1) |
| 40 | + |
| 41 | + for i := 0; i < b.N; i++ { |
| 42 | + hasher.Reset() |
| 43 | + // grab a slice of size bytes from random string |
| 44 | + hasher.Write(inputs[i : i+size]) |
| 45 | + hasher.Sum(nil) |
| 46 | + } |
| 47 | +} |
0 commit comments