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.2 kB

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