2 * Copyright 2014 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/Random.h>
18 #include <folly/Range.h>
19 #include <folly/Benchmark.h>
20 #include <folly/Foreach.h>
22 #include <glog/logging.h>
23 #include <gtest/gtest.h>
30 using namespace folly;
32 TEST(Random, StateSize) {
33 using namespace folly::detail;
35 // uint_fast32_t is uint64_t on x86_64, w00t
36 EXPECT_EQ(sizeof(uint_fast32_t) / 4 + 3,
37 StateSize<std::minstd_rand0>::value);
38 EXPECT_EQ(624, StateSize<std::mt19937>::value);
39 #if FOLLY_USE_SIMD_PRNG
40 EXPECT_EQ(624, StateSize<__gnu_cxx::sfmt19937>::value);
42 EXPECT_EQ(24, StateSize<std::ranlux24_base>::value);
45 TEST(Random, Simple) {
46 uint32_t prev = 0, seed = 0;
47 for (int i = 0; i < 1024; ++i) {
48 EXPECT_NE(seed = randomNumberSeed(), prev);
53 TEST(Random, MultiThreaded) {
55 std::vector<uint32_t> seeds(n);
56 std::vector<std::thread> threads;
57 for (int i = 0; i < n; ++i) {
58 threads.push_back(std::thread([i, &seeds] {
59 seeds[i] = randomNumberSeed();
62 for (auto& t : threads) {
65 std::sort(seeds.begin(), seeds.end());
66 for (int i = 0; i < n-1; ++i) {
67 EXPECT_LT(seeds[i], seeds[i+1]);
71 BENCHMARK(minstdrand, n) {
72 BenchmarkSuspender braces;
73 std::random_device rd;
74 std::minstd_rand rng(rd());
78 FOR_EACH_RANGE (i, 0, n) {
79 doNotOptimizeAway(rng());
83 BENCHMARK(mt19937, n) {
84 BenchmarkSuspender braces;
85 std::random_device rd;
86 std::mt19937 rng(rd());
90 FOR_EACH_RANGE (i, 0, n) {
91 doNotOptimizeAway(rng());
95 BENCHMARK(threadprng, n) {
96 BenchmarkSuspender braces;
97 ThreadLocalPRNG tprng;
102 FOR_EACH_RANGE (i, 0, n) {
103 doNotOptimizeAway(tprng());
107 BENCHMARK(RandomDouble) { doNotOptimizeAway(Random::randDouble01()); }
108 BENCHMARK(Random32) { doNotOptimizeAway(Random::rand32()); }
109 BENCHMARK(Random32Num) { doNotOptimizeAway(Random::rand32(100)); }
110 BENCHMARK(Random64) { doNotOptimizeAway(Random::rand64()); }
111 BENCHMARK(Random64Num) { doNotOptimizeAway(Random::rand64(100ul << 32)); }
112 BENCHMARK(Random64OneIn) { doNotOptimizeAway(Random::oneIn(100)); }
114 int main(int argc, char** argv) {
115 testing::InitGoogleTest(&argc, argv);
116 gflags::ParseCommandLineFlags(&argc, &argv, true);
118 if (FLAGS_benchmark) {
119 folly::runBenchmarks();
121 return RUN_ALL_TESTS();