Last active
February 27, 2024 15:53
-
-
Save Zenithar/bb55aea4ff9adaa16db95d64dab986e5 to your computer and use it in GitHub Desktop.
Run hash function benchmark on 1GB file content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto" | |
"regexp" | |
"testing" | |
_ "crypto/sha256" | |
_ "crypto/sha512" | |
_ "golang.org/x/crypto/blake2b" | |
_ "golang.org/x/crypto/sha3" | |
) | |
func main() { | |
// Run the tests | |
testing.Main(regexp.MatchString, nil, []testing.InternalBenchmark{ | |
{Name: "SHA256", F: benchmarkHash(crypto.SHA256)}, | |
{Name: "SHA384", F: benchmarkHash(crypto.SHA384)}, | |
{Name: "SHA512", F: benchmarkHash(crypto.SHA512)}, | |
{Name: "SHA512_256", F: benchmarkHash(crypto.SHA512_256)}, | |
{Name: "Blake2b_256", F: benchmarkHash(crypto.BLAKE2b_256)}, | |
{Name: "Blake2b_384", F: benchmarkHash(crypto.BLAKE2b_384)}, | |
{Name: "Blake2b_512", F: benchmarkHash(crypto.BLAKE2b_512)}, | |
{Name: "SHA3_256", F: benchmarkHash(crypto.SHA3_256)}, | |
{Name: "SHA3_384", F: benchmarkHash(crypto.SHA3_384)}, | |
{Name: "SHA3_512", F: benchmarkHash(crypto.SHA3_512)}, | |
}, nil) | |
} | |
type zeroReader struct{} | |
func (zeroReader) Read(p []byte) (int, error) { | |
for i := range p { | |
p[i] = 0 | |
} | |
return len(p), nil | |
} | |
func benchmarkHash(hf crypto.Hash) func(b *testing.B) { | |
return func(b *testing.B) { | |
// Create a new zeroReader | |
bio := zeroReader{} | |
// Create a new hash.Hash object | |
hash := hf.New() | |
// Desired content size to read | |
contentSize := 1024 * 1024 * 1024 // 1GB | |
// Read the data from the zeroReader | |
block := make([]byte, hash.BlockSize()) | |
for i := 0; i < b.N; i++ { | |
// Set the size of the content | |
b.SetBytes(int64(contentSize)) | |
// Read the content from the zeroReader | |
for n := 0; n < contentSize; n += hash.BlockSize() { | |
_, err := bio.Read(block) | |
if err != nil { | |
b.Fatal(err) | |
} | |
_, err = hash.Write(block) | |
if err != nil { | |
b.Fatal(err) | |
} | |
} | |
// Sum the hash | |
hash.Sum(nil) | |
// Reset the hash | |
hash.Reset() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment