Fix SimpleBarrier
[folly.git] / folly / test / RandomTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Random.h>
18
19 #include <glog/logging.h>
20
21 #include <algorithm>
22 #include <thread>
23 #include <vector>
24 #include <random>
25
26 #include <folly/portability/GTest.h>
27
28 using namespace folly;
29
30 TEST(Random, StateSize) {
31   using namespace folly::detail;
32
33   // uint_fast32_t is uint64_t on x86_64, w00t
34   EXPECT_EQ(sizeof(uint_fast32_t) / 4 + 3,
35             StateSize<std::minstd_rand0>::value);
36   EXPECT_EQ(624, StateSize<std::mt19937>::value);
37 #if FOLLY_HAVE_EXTRANDOM_SFMT19937
38   EXPECT_EQ(624, StateSize<__gnu_cxx::sfmt19937>::value);
39 #endif
40   EXPECT_EQ(24, StateSize<std::ranlux24_base>::value);
41 }
42
43 TEST(Random, Simple) {
44   uint32_t prev = 0, seed = 0;
45   for (int i = 0; i < 1024; ++i) {
46     EXPECT_NE(seed = randomNumberSeed(), prev);
47     prev = seed;
48   }
49 }
50
51 TEST(Random, FixedSeed) {
52   // clang-format off
53   struct ConstantRNG {
54     typedef uint32_t result_type;
55     result_type operator()() {
56       return 4; // chosen by fair dice roll.
57                 // guaranteed to be random.
58     }
59     static constexpr result_type min() {
60       return std::numeric_limits<result_type>::min();
61     }
62     static constexpr result_type max() {
63       return std::numeric_limits<result_type>::max();
64     }
65   };
66   // clang-format on
67
68   ConstantRNG gen;
69
70   // Pick a constant random number...
71   auto value = Random::rand32(10, gen);
72
73   // Loop to make sure it really is constant.
74   for (int i = 0; i < 1024; ++i) {
75     auto result = Random::rand32(10, gen);
76     EXPECT_EQ(value, result);
77   }
78 }
79
80 TEST(Random, MultiThreaded) {
81   const int n = 100;
82   std::vector<uint32_t> seeds(n);
83   std::vector<std::thread> threads;
84   for (int i = 0; i < n; ++i) {
85     threads.push_back(std::thread([i, &seeds] {
86       seeds[i] = randomNumberSeed();
87     }));
88   }
89   for (auto& t : threads) {
90     t.join();
91   }
92   std::sort(seeds.begin(), seeds.end());
93   for (int i = 0; i < n-1; ++i) {
94     EXPECT_LT(seeds[i], seeds[i+1]);
95   }
96 }