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()38inline 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 while (i < 5) { 46 try { 47 std::mt19937 random_device{std::random_device("/dev/urandom")()}; 48 return random_device; 49 } catch (const std::exception &e) { 50 MS_LOG(WARNING) << "Get std::random_device failed, retry: " << i << ", error: " << e.what(); 51 std::this_thread::sleep_for(std::chrono::milliseconds(10)); 52 i++; 53 } 54 } 55 std::mt19937 random_device{std::random_device("/dev/urandom")()}; 56 #endif 57 return random_device; 58 } 59 GetNewSeed()60inline uint32_t GetNewSeed() { 61 std::mt19937 random_device = GetRandomDevice(); 62 std::uniform_int_distribution<uint32_t> distribution(0, std::numeric_limits<uint32_t>::max()); 63 return distribution(random_device); 64 } 65 GetSeed()66inline uint32_t GetSeed() { 67 uint32_t seed = GlobalContext::config_manager()->seed(); 68 if (seed == std::mt19937::default_seed) { 69 seed = GetNewSeed(); 70 } 71 return seed; 72 } 73 74 } // namespace dataset 75 } // namespace mindspore 76 77 #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_RANDOM_H_ 78