...

Source file src/runtime/rand_test.go

Documentation: runtime

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime_test
     6  
     7  import (
     8  	. "runtime"
     9  	"strconv"
    10  	"testing"
    11  	_ "unsafe" // for go:linkname
    12  )
    13  
    14  func TestReadRandom(t *testing.T) {
    15  	if *ReadRandomFailed {
    16  		switch GOOS {
    17  		default:
    18  			t.Fatalf("readRandom failed at startup")
    19  		case "plan9":
    20  			// ok
    21  		}
    22  	}
    23  }
    24  
    25  func BenchmarkFastrand(b *testing.B) {
    26  	b.RunParallel(func(pb *testing.PB) {
    27  		for pb.Next() {
    28  			Fastrand()
    29  		}
    30  	})
    31  }
    32  
    33  func BenchmarkFastrand64(b *testing.B) {
    34  	b.RunParallel(func(pb *testing.PB) {
    35  		for pb.Next() {
    36  			Fastrand64()
    37  		}
    38  	})
    39  }
    40  
    41  func BenchmarkFastrandHashiter(b *testing.B) {
    42  	var m = make(map[int]int, 10)
    43  	for i := 0; i < 10; i++ {
    44  		m[i] = i
    45  	}
    46  	b.RunParallel(func(pb *testing.PB) {
    47  		for pb.Next() {
    48  			for range m {
    49  				break
    50  			}
    51  		}
    52  	})
    53  }
    54  
    55  var sink32 uint32
    56  
    57  func BenchmarkFastrandn(b *testing.B) {
    58  	for n := uint32(2); n <= 5; n++ {
    59  		b.Run(strconv.Itoa(int(n)), func(b *testing.B) {
    60  			for i := 0; i < b.N; i++ {
    61  				sink32 = Fastrandn(n)
    62  			}
    63  		})
    64  	}
    65  }
    66  
    67  //go:linkname fastrand runtime.fastrand
    68  func fastrand() uint32
    69  
    70  //go:linkname fastrandn runtime.fastrandn
    71  func fastrandn(uint32) uint32
    72  
    73  //go:linkname fastrand64 runtime.fastrand64
    74  func fastrand64() uint64
    75  
    76  func TestLegacyFastrand(t *testing.T) {
    77  	// Testing mainly that the calls work at all,
    78  	// but check that all three don't return the same number (1 in 2^64 chance)
    79  	{
    80  		x, y, z := fastrand(), fastrand(), fastrand()
    81  		if x == y && y == z {
    82  			t.Fatalf("fastrand three times = %#x, %#x, %#x, want different numbers", x, y, z)
    83  		}
    84  	}
    85  	{
    86  		x, y, z := fastrandn(1e9), fastrandn(1e9), fastrandn(1e9)
    87  		if x == y && y == z {
    88  			t.Fatalf("fastrandn three times = %#x, %#x, %#x, want different numbers", x, y, z)
    89  		}
    90  	}
    91  	{
    92  		x, y, z := fastrand64(), fastrand64(), fastrand64()
    93  		if x == y && y == z {
    94  			t.Fatalf("fastrand64 three times = %#x, %#x, %#x, want different numbers", x, y, z)
    95  		}
    96  	}
    97  }
    98  

View as plain text