File: Random.cpp

package info (click to toggle)
ola 0.10.9.nojsmin-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 17,440 kB
  • sloc: cpp: 132,294; python: 14,445; javascript: 7,109; sh: 4,713; ansic: 2,189; java: 518; xml: 253; makefile: 175
file content (74 lines) | stat: -rw-r--r-- 2,066 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * Random.cpp
 * Random number generator
 * Copyright (C) 2012 Simon Newton
 */

#if HAVE_CONFIG_H
#include <config.h>
#endif  // HAVE_CONFIG_H

#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#ifdef HAVE_RANDOM
#include <random>
#endif  // HAVE_RANDOM

#include "ola/Clock.h"
#include "ola/math/Random.h"

namespace ola {
namespace math {

#ifdef HAVE_RANDOM
std::default_random_engine generator_;
#endif  // HAVE_RANDOM

void InitRandom() {
  Clock clock;
  TimeStamp now;
  // The clock type here should not matter because only the microseconds field
  // is being used to seed the random number generator.
  clock.CurrentRealTime(&now);

  uint64_t seed = (static_cast<uint64_t>(now.MicroSeconds()) << 32) +
                   static_cast<uint64_t>(getpid());
#ifdef HAVE_RANDOM
  generator_.seed(seed);
#elif defined(_WIN32)
  srand(seed);
#else
  srandom(seed);
#endif  // HAVE_RANDOM
}

int Random(int lower, int upper) {
#ifdef HAVE_RANDOM
  std::uniform_int_distribution<int> distribution(lower, upper);
  return distribution(generator_);
#elif defined(_WIN32)
  return (lower +
          (rand() % (upper - lower + 1)));  // NOLINT(runtime/threadsafe_fn)
#else
  return (lower + (random() % (upper - lower + 1)));
#endif  // HAVE_RANDOM
}
}  // namespace math
}  // namespace ola