Ugly loops versus pretty vectors (R)
The other day, I posted a prototypical example of use of parLapply, somewhat more advanced than the ones in the documentation; see here.
Well, part of the example I gave uses one of my most biggest coding pet peaves, something that I have been fighting against ever since my MatLab days: the dreaded unnecessary for loop. As I was teaching myself the use of the
tictoc library, I thought I would illustrate both.
To keep in the spirit of the example in the post mentioned, we set up variations of up to two parameters, $\beta$ and $S_0$. We set base values for these parameters.
We will try different ranges of number of cases.
Now loop on the number of cases. First, clear the
tictoc log, in case it already exists. In each loop, we take note of the time taken to accomplish each group of operations.
The following is adapted from the
Add a few additional pieces of information about timing: the total time in the second case (making the vectors and converting them to lists) as well as acceleration factors when making the vector and in total of the second method.
knitr to make a decent looking table of the results.
Here are the results:
Clearly, it would be better here to use a parallel version of
apply operating on matrix rows than on lists, since this would not require a further conversion to a list. But the cases are not always this structured.
Ah, yes, one last thing: when $n$ is large, some of the variables can become quite large (the last matrix by itself is 10.1 Gb). Unless you have pretty decent RAM, don’t try this at home.