I have written a stochastic process simulator but I would like to speed it up since it's pretty slow.
The main part of the simulator is made of a for
loop which I would like to re-write as a foreach
with `%dopar%.
I have tried doing so with a simplified loop but I'm running into some problems. Suppose my for
loop looks like this
library(foreach)
r=0
t<-rep(0,500)
for(n in 1:500){
s<-1/2+r
u<-runif(1, min = 0, max = 1)
if(u<s){
t[n]<-u
r<-r+0.001
}else{r<-r-0.001}
}
which means that at each iteration I update the value of r
and s
and, in one of the two outcomes, populate my vector t
. I have tried several different ways of re-writing it as a foreach
loop but it seems like with each iteration my values don't get updated and I get some pretty strange results. I have tried using return
but it doesn't seem to work!
This is an example of what I have come up with.
rr=0
tt<-foreach(i=1:500, .combine=c) %dopar% {
ss<-1/2+rr
uu<-runif(1, min = 0, max = 1)
if(uu<=ss){
return(uu)
rr<-rr+0.001
}else{
return(0)
rr<-rr-0.001}
}
If it is impossible to use foreach
what other way is there for me to re-write the loop so to be able to use all cores and speed up things?
Since your comments, about turning to C, were encouraging and -mostly- to prove that this isn't a hard task (especially for such operations) and it's worth looking into, here is a comparison of two sample functions that accept a number of iterations and perform the steps of your loop:
A comparison of results:
A comparison of speed:
And for the sake of completeness:
Hope any of this could be helpful in some way.