Browse Source

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 <chinsyo@sina.cn>
Chinsyo 5 years ago
parent
commit
bdf715afa9
2 changed files with 19 additions and 1 deletions
  1. 1 1
      common/dice/dice.go
  2. 18 0
      common/dice/dice_test.go

+ 1 - 1
common/dice/dice.go

@@ -25,7 +25,7 @@ func RollDeterministic(n int, seed int64) int {
 
 
 // RollUint16 returns a random uint16 value.
 // RollUint16 returns a random uint16 value.
 func RollUint16() uint16 {
 func RollUint16() uint16 {
-	return uint16(rand.Intn(65536))
+	return uint16(rand.Int63() >> 47)
 }
 }
 
 
 func RollUint64() uint64 {
 func RollUint64() uint64 {

+ 18 - 0
common/dice/dice_test.go

@@ -30,3 +30,21 @@ func BenchmarkIntn20(b *testing.B) {
 		rand.Intn(20)
 		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))
+	}
+}