Re: [PATCH net-next v2 1/2] random: add prandom_u32_range andprandom_u32_max helpers

From: Joe Perches
Date: Wed Sep 04 2013 - 12:26:30 EST


On Wed, 2013-09-04 at 14:37 +0200, Daniel Borkmann wrote:
> We have implemented the same function over and over, so introduce
> generic helpers that unify these implementations in order to migrate
> such code to use them. Make the API similarly to randomize_range()
> for consistency. prandom_u32_range() generates numbers in [start, end]
> interval and prandom_u32_max() generates numbers in [0, end] interval.

I think these helpers can in many cases cause
poorer compiler generated object code.

> +/**
> + * prandom_u32_range - return a random number in interval [start, end]
> + * @start: lower interval endpoint
> + * @end: higher interval endpoint
> + *
> + * Returns a number that is in the given interval:
> + *
> + * [...... <range> .....]
> + * start end
> + *
> + * Callers need to make sure that start <= end. Note that the result
> + * depends on PRNG being well distributed in [0, ~0U] space. Here we
> + * use maximally equidistributed combined Tausworthe generator.
> + */
> +static inline u32 prandom_u32_range(u32 start, u32 end)
> +{
> + return (u32)(((u64) prandom_u32() * (end + 1 - start)) >> 32) + start;
> +}

This is effectively:

return (prandom_u32() % (end - start)) + start;

and if start and end are constant, gcc can optimize the
division by constant to a 32 bit multiply/shift/add.

I think if you add __builtin_constant_p tests for start
and end and expand the code a little you can still get
the optimizations done.

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/