github.com/creachadair/ffs@v0.17.3/file/bench_test.go (about)

     1  // Copyright 2020 Michael J. Fromberger. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package file_test
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  	"unsafe"
    21  )
    22  
    23  func isZeroUnsafe(data []byte) bool {
    24  	n := len(data)
    25  	m := n &^ 7
    26  
    27  	i := 0
    28  	for ; i < m; i += 8 {
    29  		v := *(*uint64)(unsafe.Pointer(&data[i]))
    30  		if v != 0 {
    31  			return false
    32  		}
    33  	}
    34  	for ; i < n; i++ {
    35  		if data[i] != 0 {
    36  			return false
    37  		}
    38  	}
    39  	return true
    40  }
    41  
    42  func isZeroSafe(data []byte) bool {
    43  	for _, b := range data {
    44  		if b != 0 {
    45  			return false
    46  		}
    47  	}
    48  	return true
    49  }
    50  
    51  func BenchmarkZeroTest(b *testing.B) {
    52  	// N.B. Sizes chosen for the worst case of the unsafe implementation,
    53  	// leaving a 7-byte tail.
    54  	sizes := []int{103, 1007, 10007, 100007}
    55  
    56  	for _, size := range sizes {
    57  		buf := make([]byte, size)
    58  		b.Run(fmt.Sprintf("Unsafe-%d", size), func(b *testing.B) {
    59  			for i := 0; i < b.N; i++ {
    60  				isZeroUnsafe(buf)
    61  			}
    62  		})
    63  		b.Run(fmt.Sprintf("Safe-%d", size), func(b *testing.B) {
    64  			for i := 0; i < b.N; i++ {
    65  				isZeroSafe(buf)
    66  			}
    67  		})
    68  	}
    69  }