github.com/prysmaticlabs/prysm@v1.4.4/shared/mputil/benchmark_test.go (about)

     1  package mputil_test
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/sha256"
     6  	"sync"
     7  	"testing"
     8  
     9  	"github.com/prysmaticlabs/prysm/shared/mputil"
    10  	"github.com/prysmaticlabs/prysm/shared/testutil/require"
    11  	log "github.com/sirupsen/logrus"
    12  )
    13  
    14  var input [][]byte
    15  
    16  const (
    17  	benchmarkElements    = 65536
    18  	benchmarkElementSize = 32
    19  	benchmarkHashRuns    = 128
    20  )
    21  
    22  func init() {
    23  	input = make([][]byte, benchmarkElements)
    24  	for i := 0; i < benchmarkElements; i++ {
    25  		input[i] = make([]byte, benchmarkElementSize)
    26  		_, err := rand.Read(input[i])
    27  		if err != nil {
    28  			log.WithError(err).Debug("Cannot read from rand")
    29  		}
    30  	}
    31  }
    32  
    33  // hash repeatedly hashes the data passed to it
    34  func hash(input [][]byte) [][]byte {
    35  	output := make([][]byte, len(input))
    36  	for i := range input {
    37  		copy(output, input)
    38  		for j := 0; j < benchmarkHashRuns; j++ {
    39  			hash := sha256.Sum256(output[i])
    40  			output[i] = hash[:]
    41  		}
    42  	}
    43  	return output
    44  }
    45  
    46  func BenchmarkHash(b *testing.B) {
    47  	for i := 0; i < b.N; i++ {
    48  		hash(input)
    49  	}
    50  }
    51  
    52  func BenchmarkHashMP(b *testing.B) {
    53  	output := make([][]byte, len(input))
    54  	for i := 0; i < b.N; i++ {
    55  		workerResults, err := mputil.Scatter(len(input), func(offset int, entries int, _ *sync.RWMutex) (interface{}, error) {
    56  			return hash(input[offset : offset+entries]), nil
    57  		})
    58  		require.NoError(b, err)
    59  		for _, result := range workerResults {
    60  			copy(output[result.Offset:], result.Extent.([][]byte))
    61  		}
    62  	}
    63  }