performance tuning - Are there rules of thumb for knowing when RandomVariate is more efficient than RandomReal?
Please consider the following:
From a fresh Mathematica kernel, RandomVariate
is more efficient for NormalDistribution
but RandomReal
is for uniformly distributed noise.
RandomReal[NormalDistribution[0, 1], 100]; // Timing
{0.00535, Null}
RandomVariate[NormalDistribution[0, 1], 100]; // Timing
{0.000069, Null}
RandomReal[{0, 1}, 100]; // Timing
{0.00004, Null}
RandomVariate[UniformDistribution[], 100]; // Timing
{0.005236, Null}
But if I re-evaluate, I get Timing
results that are much more similar:
RandomReal[NormalDistribution[0, 1], 100]; // Timing
{0.000051, Null}
RandomVariate[NormalDistribution[0, 1], 100]; // Timing
{0.000052, Null}
RandomReal[{0, 1}, 100]; // Timing
{0.00003, Null}
RandomVariate[UniformDistribution[], 100]; // Timing
{0.000058, Null}
Does caching the distribution definition really matter that much?
Obviously RandomVariate
has the advantage that it can generate data from mixed (not only fully continuous or fully discrete) distributions. So it is more general. But if one is generating random numbers from standard distributions like the normal or the Poisson, is there any advantage – performance or otherwise – to using RandomVariate
instead of RandomReal
or RandomInteger
?
Answer
In general you should use RandomVariate
for distributions and RandomReal
for uniforms. Often RandomVariate
calls RandomReal
or RandomInteger
under the hood but it varies on a distribution by distribution basis. After loading any necessary symbols, on evaluation, any timing differences should be negligible.
RandomVariate
is intended to give the flexibility to not have to think of whether the distribution is continuous or discrete (or mixed), it has also been optimized for each distribution in the system. One should always be able to use RandomInteger
or RandomReal
if the type is known ahead of time (and is not mixed or fuzzy in some way e.g. EmpiricalDistribution
) but again, most of the overhead is in initializing the generator so if you are generating a large number of random numbers you shouldn't notice a big difference in timings after evaluating both RandomVariate
and RandomReal
/RandomInteger
.
Comments
Post a Comment