RandomBenchmark.cpp 2.1 KB

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