rand_util_unittest.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "butil/rand_util.h"
  5. #include "butil/fast_rand.h"
  6. #include "butil/time.h"
  7. #include <algorithm>
  8. #include <limits>
  9. #include "butil/logging.h"
  10. #include "butil/memory/scoped_ptr.h"
  11. #include "butil/time/time.h"
  12. #include <gtest/gtest.h>
  13. namespace {
  14. const int kIntMin = std::numeric_limits<int>::min();
  15. const int kIntMax = std::numeric_limits<int>::max();
  16. } // namespace
  17. TEST(RandUtilTest, Sanity) {
  18. EXPECT_EQ(butil::RandInt(0, 0), 0);
  19. EXPECT_EQ(butil::RandInt(kIntMin, kIntMin), kIntMin);
  20. EXPECT_EQ(butil::RandInt(kIntMax, kIntMax), kIntMax);
  21. for (int i = 0; i < 10; ++i) {
  22. uint64_t value = butil::fast_rand_in(
  23. (uint64_t)0, std::numeric_limits<uint64_t>::max());
  24. if (value != std::numeric_limits<uint64_t>::min() &&
  25. value != std::numeric_limits<uint64_t>::max()) {
  26. break;
  27. } else {
  28. EXPECT_NE(9, i) << "Never meet random except min/max of uint64";
  29. }
  30. }
  31. for (int i = 0; i < 10; ++i) {
  32. int64_t value = butil::fast_rand_in(
  33. std::numeric_limits<int64_t>::min(),
  34. std::numeric_limits<int64_t>::max());
  35. if (value != std::numeric_limits<int64_t>::min() &&
  36. value != std::numeric_limits<int64_t>::max()) {
  37. break;
  38. } else {
  39. EXPECT_NE(9, i) << "Never meet random except min/max of int64";
  40. }
  41. }
  42. EXPECT_EQ(butil::fast_rand_in(-1, -1), -1);
  43. EXPECT_EQ(butil::fast_rand_in(1, 1), 1);
  44. EXPECT_EQ(butil::fast_rand_in(0, 0), 0);
  45. EXPECT_EQ(butil::fast_rand_in(std::numeric_limits<int64_t>::min(),
  46. std::numeric_limits<int64_t>::min()),
  47. std::numeric_limits<int64_t>::min());
  48. EXPECT_EQ(butil::fast_rand_in(std::numeric_limits<int64_t>::max(),
  49. std::numeric_limits<int64_t>::max()),
  50. std::numeric_limits<int64_t>::max());
  51. EXPECT_EQ(butil::fast_rand_in(std::numeric_limits<uint64_t>::min(),
  52. std::numeric_limits<uint64_t>::min()),
  53. std::numeric_limits<uint64_t>::min());
  54. EXPECT_EQ(butil::fast_rand_in(std::numeric_limits<uint64_t>::max(),
  55. std::numeric_limits<uint64_t>::max()),
  56. std::numeric_limits<uint64_t>::max());
  57. }
  58. TEST(RandUtilTest, RandDouble) {
  59. // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
  60. volatile double number = butil::RandDouble();
  61. EXPECT_GT(1.0, number);
  62. EXPECT_LE(0.0, number);
  63. volatile double number2 = butil::fast_rand_double();
  64. EXPECT_GT(1.0, number2);
  65. EXPECT_LE(0.0, number2);
  66. }
  67. TEST(RandUtilTest, RandBytes) {
  68. const size_t buffer_size = 50;
  69. char buffer[buffer_size];
  70. memset(buffer, 0, buffer_size);
  71. butil::RandBytes(buffer, buffer_size);
  72. std::sort(buffer, buffer + buffer_size);
  73. // Probability of occurrence of less than 25 unique bytes in 50 random bytes
  74. // is below 10^-25.
  75. EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
  76. }
  77. TEST(RandUtilTest, RandBytesAsString) {
  78. std::string random_string = butil::RandBytesAsString(1);
  79. EXPECT_EQ(1U, random_string.size());
  80. random_string = butil::RandBytesAsString(145);
  81. EXPECT_EQ(145U, random_string.size());
  82. char accumulator = 0;
  83. for (size_t i = 0; i < random_string.size(); ++i) {
  84. accumulator |= random_string[i];
  85. }
  86. // In theory this test can fail, but it won't before the universe dies of
  87. // heat death.
  88. EXPECT_NE(0, accumulator);
  89. }
  90. // Make sure that it is still appropriate to use RandGenerator in conjunction
  91. // with std::random_shuffle().
  92. TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
  93. EXPECT_EQ(butil::RandGenerator(1), 0U);
  94. EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
  95. std::numeric_limits<int64_t>::max());
  96. }
  97. TEST(RandUtilTest, RandGeneratorIsUniform) {
  98. // Verify that RandGenerator has a uniform distribution. This is a
  99. // regression test that consistently failed when RandGenerator was
  100. // implemented this way:
  101. //
  102. // return butil::RandUint64() % max;
  103. //
  104. // A degenerate case for such an implementation is e.g. a top of
  105. // range that is 2/3rds of the way to MAX_UINT64, in which case the
  106. // bottom half of the range would be twice as likely to occur as the
  107. // top half. A bit of calculus care of jar@ shows that the largest
  108. // measurable delta is when the top of the range is 3/4ths of the
  109. // way, so that's what we use in the test.
  110. const uint64_t kTopOfRange = (std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL;
  111. const uint64_t kExpectedAverage = kTopOfRange / 2ULL;
  112. const uint64_t kAllowedVariance = kExpectedAverage / 50ULL; // +/- 2%
  113. const int kMinAttempts = 1000;
  114. const int kMaxAttempts = 1000000;
  115. for (int round = 0; round < 2; ++round) {
  116. LOG(INFO) << "Use " << (round == 0 ? "RandUtil" : "fast_rand");
  117. double cumulative_average = 0.0;
  118. int count = 0;
  119. while (count < kMaxAttempts) {
  120. uint64_t value = (round == 0 ? butil::RandGenerator(kTopOfRange)
  121. : butil::fast_rand_less_than(kTopOfRange));
  122. cumulative_average = (count * cumulative_average + value) / (count + 1);
  123. // Don't quit too quickly for things to start converging, or we may have
  124. // a false positive.
  125. if (count > kMinAttempts &&
  126. double(kExpectedAverage - kAllowedVariance) < cumulative_average &&
  127. cumulative_average < double(kExpectedAverage + kAllowedVariance)) {
  128. break;
  129. }
  130. ++count;
  131. }
  132. ASSERT_LT(count, kMaxAttempts) << "Expected average was " <<
  133. kExpectedAverage << ", average ended at " << cumulative_average;
  134. }
  135. }
  136. TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
  137. // This tests to see that our underlying random generator is good
  138. // enough, for some value of good enough.
  139. const uint64_t kAllZeros = 0ULL;
  140. const uint64_t kAllOnes = ~kAllZeros;
  141. for (int round = 0; round < 2; ++round) {
  142. LOG(INFO) << "Use " << (round == 0 ? "RandUtil" : "fast_rand");
  143. uint64_t found_ones = kAllZeros;
  144. uint64_t found_zeros = kAllOnes;
  145. bool fail = true;
  146. for (size_t i = 0; i < 1000; ++i) {
  147. uint64_t value = (round == 0 ? butil::RandUint64() : butil::fast_rand());
  148. found_ones |= value;
  149. found_zeros &= value;
  150. if (found_zeros == kAllZeros && found_ones == kAllOnes) {
  151. fail = false;
  152. break;
  153. }
  154. }
  155. if (fail) {
  156. FAIL() << "Didn't achieve all bit values in maximum number of tries.";
  157. }
  158. }
  159. }
  160. // Benchmark test for RandBytes(). Disabled since it's intentionally slow and
  161. // does not test anything that isn't already tested by the existing RandBytes()
  162. // tests.
  163. TEST(RandUtilTest, DISABLED_RandBytesPerf) {
  164. // Benchmark the performance of |kTestIterations| of RandBytes() using a
  165. // buffer size of |kTestBufferSize|.
  166. const int kTestIterations = 10;
  167. const size_t kTestBufferSize = 1 * 1024 * 1024;
  168. scoped_ptr<uint8_t[]> buffer(new uint8_t[kTestBufferSize]);
  169. const butil::TimeTicks now = butil::TimeTicks::HighResNow();
  170. for (int i = 0; i < kTestIterations; ++i) {
  171. butil::RandBytes(buffer.get(), kTestBufferSize);
  172. }
  173. const butil::TimeTicks end = butil::TimeTicks::HighResNow();
  174. LOG(INFO) << "RandBytes(" << kTestBufferSize << ") took: "
  175. << (end - now).InMicroseconds() << "ms";
  176. }
  177. TEST(RandUtilTest, fast_rand_perf) {
  178. const int kTestIterations = 1000000;
  179. const int kRange = 17;
  180. uint64_t s = 0;
  181. butil::Timer tm;
  182. tm.start();
  183. for (int i = 0; i < kTestIterations; ++i) {
  184. s += butil::fast_rand_less_than(kRange);
  185. }
  186. tm.stop();
  187. LOG(INFO) << "Each fast_rand_less_than took " << tm.n_elapsed() / kTestIterations
  188. << " ns, "
  189. #if !defined(NDEBUG)
  190. << " (debugging version)";
  191. #else
  192. ;
  193. #endif
  194. }