HPCToolkit
randomizer.c
Go to the documentation of this file.
1 /*
2  * randomizer.c
3  *
4  */
5 
6 //******************************************************************************
7 // global includes
8 //******************************************************************************
9 
10 #include <stdlib.h>
11 #include <values.h>
12 
13 
14 //******************************************************************************
15 // local includes
16 //******************************************************************************
17 
18 #include "urand.h"
19 #include "randomizer.h"
20 
21 
22 int
23 random_level(int max_height)
24 {
25  // generate random numbers with the required distribution by finding the
26  // position of the first one in a random number. if the first one bit is
27  // in position > max_height, we can wrap it back to a value in
28  // [0 .. max_height-1] with a mod without disturbing the integrity of the
29  // distribution.
30 
31  // a random number with the top bit set. knowing that SOME bit is set avoids
32  // the need to handle the special case where no bit is set.
33  unsigned int random = (unsigned int) (urand() | (1 << (INTBITS - 1)));
34 
35  // the following statement will count the trailing zeros in random.
36  int first_one_position = __builtin_ctz(random);
37 
38  if (first_one_position >= max_height) {
39  // wrapping a value >= maxheight with a mod operation preserves the
40  // integrity of the desired distribution.
41  first_one_position %= max_height;
42  }
43 
44  // post-condition: first_one_pos is a random level [0 .. max_height-1]
45  // with the desired distribution, assuming that urand() provides a uniform
46  // random distribution.
47 
48  // return a random level [1 .. max_height] with the desired distribution.
49  return first_one_position + 1;
50 }
51 
52 #define UNIT_TEST___random_level 0
53 #if UNIT_TEST___random_level
54 
55 #include <stdio.h>
56 #include <assert.h>
57 
58 // test that the random levels for skip list node heights have the proper
59 // distribution between 1 .. max_height, where the probability of 2^h is
60 // half that of 2^(h-1), for h in [2 .. max_height]
61 int main()
62 {
63  int bins[15];
64 
65  for (int i = 0; i < 15; i++) bins[i] = 0;
66 
67  for (int i = 0; i < 10000 * 1024 ; i++) {
68  int j = random_level(10);
69  assert(1 <= j && j <= 15);
70  bins[j-1]++;
71  }
72  for (int i = 0; i < 15;i++)
73  printf("bin[%d] = %d\n", i, bins[i]);
74 }
75 
76 #endif
77 
int urand()
Definition: urand.c:111
int random_level(int max_height)
Definition: randomizer.c:23
int main(int argc, char *argv[])
Definition: main.cpp:125