In the process of playing around with Compile
, I discovered something surprising. RandomReal[{-1, 1}, 3]
is a lot slower than Compile[{}, RandomReal[{-1, 1}, 3]]
. What could account for this? I would have imagined the two would have similar speeds.
Here's exactly what I did. First a simple timer:
compareTiming[f1_, f2_, its_] :=
With[{
tf1 = First@AbsoluteTiming[Scan[f1, Range[its]]],
tf2 = First@AbsoluteTiming[Scan[f2, Range[its]]]},
(tf2 - tf1)/Max@{tf1, tf2}
]
then:
In[115]:= randomReal3 = Compile[{}, RandomReal[{-1, 1}, 3]];
randomReal3U = Function[RandomReal[{-1, 1}, 3]];
compareTiming[randomReal3[] &, randomReal3U, 10^6]
Out[117]= 0.131774
So the compiled form is 13% faster than the uncompiled form? But RandomReal
is built-in and so I would have assumed is already implemented at the C level. What could be causing this?
I understand that I can, of course, generate a huge list of random vectors using RandomReal[{-1, 1}, {10^8, 3}]
or something but it would be nice to know why, when I need to get a large number of random vectors one at a time (absent something like storing $10^8$ of then and pulling randomly) the fastest way to do this is with a compiled version of a built-in function.
Compile
does some argument checking during the compilation, whichRandomReal[]
might do at run-time. Also, getting just3
random numbers means the overhead is a higher proportion. With a sample size of300000
, I get that the uncompiled version is faster. $\endgroup$Do
instead ofScan
, too. $\endgroup$Do[i, {i, Range[10^6]}]
, yes? But I too get that it's much faster to use theDo
imp. $\endgroup$