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