You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

random.h 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  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. #ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_RANDOM_H_
  17. #define MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_RANDOM_H_
  18. #if defined(_WIN32) || defined(_WIN64)
  19. #ifndef _CRT_RAND_S
  20. #define _CRT_RAND_S
  21. #endif
  22. #include <stdlib.h>
  23. #endif
  24. #include <chrono>
  25. #include <limits>
  26. #include <memory>
  27. #include <random>
  28. #include <string>
  29. #include <thread>
  30. #include "minddata/dataset/core/config_manager.h"
  31. #include "minddata/dataset/core/global_context.h"
  32. #include "minddata/dataset/util/log_adapter.h"
  33. namespace mindspore {
  34. namespace dataset {
  35. inline std::mt19937 GetRandomDevice() {
  36. #if defined(_WIN32) || defined(_WIN64)
  37. unsigned int number;
  38. rand_s(&number);
  39. std::mt19937 random_device{static_cast<uint32_t>(number)};
  40. #else
  41. int i = 0;
  42. while (i < 5) {
  43. try {
  44. std::mt19937 random_device{std::random_device("/dev/urandom")()};
  45. return random_device;
  46. } catch (const std::exception &e) {
  47. MS_LOG(WARNING) << "Get std::random_device failed, retry: " << i << ", error: " << e.what();
  48. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  49. i++;
  50. }
  51. }
  52. std::mt19937 random_device{std::random_device("/dev/urandom")()};
  53. #endif
  54. return random_device;
  55. }
  56. inline uint32_t GetNewSeed() {
  57. std::mt19937 random_device = GetRandomDevice();
  58. std::uniform_int_distribution<uint32_t> distribution(0, std::numeric_limits<uint32_t>::max());
  59. return distribution(random_device);
  60. }
  61. inline uint32_t GetSeed() {
  62. uint32_t seed = GlobalContext::config_manager()->seed();
  63. if (seed == std::mt19937::default_seed) {
  64. seed = GetNewSeed();
  65. }
  66. return seed;
  67. }
  68. } // namespace dataset
  69. } // namespace mindspore
  70. #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_RANDOM_H_