From bdf715afa9dc68df2e3dd248ac0bf57d32dd2c4e Mon Sep 17 00:00:00 2001 From: Chinsyo Date: Sat, 14 Nov 2020 13:00:25 +0800 Subject: [PATCH] rand.Intn(65536) -> rand.Int63() >> 47 (#417) * Optimize rand.Intn(65536) to rand.Int31() >> 15, with ~20% performance improvement. * Optimize rand.Intn(65536) to rand.rand.Int63() >> 47 * Remove rand.Seed call duplicate with original source code Co-authored-by: Chinsyo --- common/dice/dice.go | 2 +- common/dice/dice_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/common/dice/dice.go b/common/dice/dice.go index 150a76134..39d771aed 100644 --- a/common/dice/dice.go +++ b/common/dice/dice.go @@ -25,7 +25,7 @@ func RollDeterministic(n int, seed int64) int { // RollUint16 returns a random uint16 value. func RollUint16() uint16 { - return uint16(rand.Intn(65536)) + return uint16(rand.Int63() >> 47) } func RollUint64() uint64 { diff --git a/common/dice/dice_test.go b/common/dice/dice_test.go index 09b1dd4d3..05b364967 100644 --- a/common/dice/dice_test.go +++ b/common/dice/dice_test.go @@ -30,3 +30,21 @@ func BenchmarkIntn20(b *testing.B) { rand.Intn(20) } } + +func BenchmarkInt31(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = uint16(rand.Int31() >> 15) + } +} + +func BenchmarkInt63(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = uint16(rand.Int63() >> 47) + } +} + +func BenchmarkIntn(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = uint16(rand.Intn(65536)) + } +}