This question is about the runtime of the function RandomVariate.

Take a simple normalized Gaussian distribution G on the real line, I tried to generate N random variates of the distribution in two ways. The first way is simply to make a table:

Table[RandomVariate[G], {k, 1, N}]

The second way is to use the command:

RandomVariate[G, N]

From what I understood in the documentation, these two commands should be equivalent. However, when I checked the runtime, I found something surprising:

Timing[RandomVariate[G, 1]]                  =0.7348,
Timing[Table[RandomVariate[G],{k,1,N}]]      =0.7664

Timing[RandomVariate[G, 10]]                 =0.7289,
Timing[Table[RandomVariate[G],{k,1,N}]]      =8.1465

Timing[RandomVariate[G, 10^7]]               =2.4998

It seems to me that the runtime of the command involving Table scales with the number of variates, while the command without table barely does. This is pretty confusing to me. What property of the RandomVariate[G, N] command makes it so much faster than the naive table?


1 Answer 1


Generally speaking, avoiding Table would at the very least cut down on function call overhead. But in the specific case of random number generation, the setup of the Random* machinery is the more time consuming part; generating the variates is comparatively much easier.

This is mentioned in this tutorial on Random number generation as well:

The two-argument interface provides a convenient way to obtain multiple random numbers at once. Even more importantly, there is a significant efficiency advantage to generating a large number of pseudorandom numbers at once.

For statistical distributions, the speed advantage of generating many numbers at once can be even greater. In addition to the efficiency benefit inherited from the uniform number generators used, many statistical distributions also benefit from vectorized evaluation of elementary and special functions. For instance, WeibullDistribution benefits from vector evaluations of the elementary functions Power, Times, and Log.

So again asking RandomVariate for multiple values allows you to cut down on repetitive setup tasks. As an aside, you are better off using AbsoluteTiming rather than Timing when making such comparisons.

See also:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.