simplify random code

This commit is contained in:
Laurent Perron
2021-11-27 21:55:58 +01:00
parent 68183ee9d9
commit 5e9d7ab240
3 changed files with 2 additions and 57 deletions

View File

@@ -11,24 +11,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#if defined(__GNUC__)
#include <unistd.h>
#if defined(__linux__)
#include <linux/limits.h>
#endif
#endif
#if defined(_MSC_VER)
#include <Winsock2.h>
#include <windows.h>
#define PATH_MAX 4096
#else
#include <sys/time.h>
#endif
#include <cstring>
#include <ctime>
#include <random>
#include "ortools/base/hash.h"
#include "ortools/base/random.h"
namespace operations_research {
@@ -47,47 +34,8 @@ uint64_t ACMRandom::operator()(uint64_t val_max) {
return val_max == 0 ? 0 : Next64() % val_max;
}
namespace {
static inline uint32_t Word32At(const char* ptr) {
return ((static_cast<uint32_t>(ptr[0])) +
(static_cast<uint32_t>(ptr[1]) << 8) +
(static_cast<uint32_t>(ptr[2]) << 16) +
(static_cast<uint32_t>(ptr[3]) << 24));
}
} // namespace
int32_t ACMRandom::HostnamePidTimeSeed() {
char name[PATH_MAX + 20]; // need 12 bytes for 3 'empty' uint32_t's
assert(sizeof(name) - PATH_MAX > sizeof(uint32_t) * 3);
if (gethostname(name, PATH_MAX) != 0) {
strcpy(name, "default-hostname"); // NOLINT
}
const int namelen = strlen(name);
for (size_t i = 0; i < sizeof(uint32_t) * 3; ++i) {
name[namelen + i] = '\0'; // so we mix 0's once we get to end-of-string
}
#if defined(__GNUC__)
uint32_t a = getpid();
struct timeval tv;
gettimeofday(&tv, NULL);
uint32_t b = static_cast<uint32_t>((tv.tv_sec + tv.tv_usec) & 0xffffffff);
#elif defined(_MSC_VER)
uint32_t a = GetCurrentProcessId();
uint32_t b = GetTickCount();
#else // Do not know what to do, returning 0.
return 0;
#endif
uint32_t c = 0;
for (int i = 0; i < namelen; i += sizeof(uint32_t) * 3) {
a += Word32At(name + i);
b += Word32At(name + i + sizeof(uint32_t));
c += Word32At(name + i + sizeof(uint32_t) + sizeof(uint32_t));
mix(a, b, c);
}
c += namelen; // one final mix
mix(a, b, c);
return static_cast<int32_t>(c); // I guess the seed can be negative
return std::random_device{}();
}
int32_t ACMRandom::DeterministicSeed() { return 0; }

View File

@@ -59,8 +59,6 @@ class MTRandom : public ACMRandom {
explicit MTRandom(const std::string& str_seed)
: ACMRandom(GenerateInt32SeedFromString(str_seed)) {}
MTRandom() : ACMRandom(ACMRandom::HostnamePidTimeSeed()) {}
private:
int32_t GenerateInt32SeedFromString(const std::string& str) {
uint32_t seed = 1234567;

View File

@@ -23,7 +23,6 @@
#include "ortools/algorithms/dynamic_partition.h"
#include "ortools/base/adjustable_priority_queue-inl.h"
#include "ortools/base/logging.h"
#include "ortools/base/random.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.h"
#include "ortools/base/timer.h"