Optimization of custom probability distibutions?

Consider the two tests:

Timing[Do[RandomVariate[NormalDistribution[0.5, 0.3]], {200}]]

{0.001188, Null}

MyNormalDistribution[mu_,sig_] = ProbabilityDistribution[1/(Sqrt[2 \[Pi]]sig)
Exp[-(x - mu)^2/(2 sig^2))], {x, -\[Infinity], \[Infinity]}];
Timing[Do[RandomVariate[MyNormalDistribution[0.5, 0.3]], {200}]]

{3.375444, Null}

So it seems that the built in normal distribution is much faster (~3000 times faster!) then the custom one. My question is how is this optimization done and whether it can be implemented for custom distributions as well?

• Related questions: (1124), (20067), (56180), (75303) – dr.blochwave Apr 24 '15 at 14:56
• In particular question #1124 – dr.blochwave Apr 24 '15 at 14:58
• The LHS of your definition should read MyNormalDistribution[mu_, sig_] Without the patterns, MyNormalDistribution[0.5, 0.3] is undefined. Even after this correction, RandomVariate[MyNormalDistribution[0.5, 0.3]] does not return a value. RandomVariate only works with the built-in distributions. You would need to define an upvalue for MyNormalDistribution to have RandomVariate work. – Bob Hanlon Apr 24 '15 at 16:16
• @BobHanlon, You are right about the missing underscores, thanks. This was a typo. However, RandomVariate does work with custom distributions (at least in v10). Feel free to try it yourself.... – JeffDror Apr 24 '15 at 16:45
• Do you really require them one at a time? Is the distribution changing between calls (only real reason I can think of that would need singlets)? Otherwise, produce them in bulk, will be orders of magnitude faster. – ciao Apr 13 '16 at 5:29