I am trying to populate a region of data with randomness using rand
cross-platform in an efficient way. Here is what I have so far:
/**********************************************\
* Useful macro by Glen Ragen *
* http://ift.tt/2rsrYb9 *
\**********************************************/
#if 1 /* So that the IDE minifies it */
#define NEEDS_BIT(N, B) (((unsigned long)N >> B) > 0)
#define BITS_TO_REPRESENT(N) \
(NEEDS_BIT(N, 0) + NEEDS_BIT(N, 1) + \
NEEDS_BIT(N, 2) + NEEDS_BIT(N, 3) + \
...
NEEDS_BIT(N, 60) + NEEDS_BIT(N, 61) + \
NEEDS_BIT(N, 62) + NEEDS_BIT(N, 63) \
)
#endif /* So that the IDE minifies it */
typedef struct {
size_t size; /* Size in bytes */
void *pointer;
} data;
void fill_data_with_randomness(const data data) {
for (size_t biti = 0; biti < data.size * 8; biti += BITS_TO_REPRESENT(RAND_MAX)) {
/* Fill data.pointer with bits from rand() */
}
}
As RAND_MAX
is a compile-time constant, BITS_TO_REPRESENT(RAND_MAX)
also should be. As data
is of type const data
, data.size * 8
should be able to be optimised to a call-time constant and not evaluated every iteration of the for loop.
However, bit manipulation is quite slow and the fill_data_with_randomness
function will be called very frequently. This function should compile for and run correctly on systems with any value of RAND_MAX
of form 2^n-1. How can I quickly fill this region of memory with rand()
mness without wasting bits?
Aucun commentaire:
Enregistrer un commentaire