b0991f178e64c162a657d751906a11c075b858e5
[folly.git] / folly / test / RandomBenchmark.cpp
1 /*
2  * Copyright 2017 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 <folly/Benchmark.h>
20 #include <folly/Foreach.h>
21
22 #include <glog/logging.h>
23
24 #include <thread>
25 #include <random>
26
27 using namespace folly;
28
29 BENCHMARK(minstdrand, n) {
30   BenchmarkSuspender braces;
31   std::random_device rd;
32   std::minstd_rand rng(rd());
33
34   braces.dismiss();
35
36   FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); }
37 }
38
39 BENCHMARK(mt19937, n) {
40   BenchmarkSuspender braces;
41   std::random_device rd;
42   std::mt19937 rng(rd());
43
44   braces.dismiss();
45
46   FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); }
47 }
48
49 #if FOLLY_HAVE_EXTRANDOM_SFMT19937
50 BENCHMARK(sfmt19937, n) {
51   BenchmarkSuspender braces;
52   std::random_device rd;
53   __gnu_cxx::sfmt19937 rng(rd());
54
55   braces.dismiss();
56
57   FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); }
58 }
59 #endif
60
61 BENCHMARK(threadprng, n) {
62   BenchmarkSuspender braces;
63   ThreadLocalPRNG tprng;
64   tprng();
65
66   braces.dismiss();
67
68   FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(tprng()); }
69 }
70
71 BENCHMARK(RandomDouble) { doNotOptimizeAway(Random::randDouble01()); }
72 BENCHMARK(Random32) { doNotOptimizeAway(Random::rand32()); }
73 BENCHMARK(Random32Num) { doNotOptimizeAway(Random::rand32(100)); }
74 BENCHMARK(Random64) { doNotOptimizeAway(Random::rand64()); }
75 BENCHMARK(Random64Num) { doNotOptimizeAway(Random::rand64(100ull << 32)); }
76 BENCHMARK(Random64OneIn) { doNotOptimizeAway(Random::oneIn(100)); }
77
78 int main(int argc, char** argv) {
79   gflags::ParseCommandLineFlags(&argc, &argv, true);
80   folly::runBenchmarks();
81   return 0;
82 }