简体   繁体   中英

How to make this loop faster

it takes about an hour to this loop. Is there any way make this faster?

l <- 2

while (l < 300001) {
  VV[1,l] = log(b+(l-1) * 0.001-0.0005) + k + 
    beta * (1-delta) * (1-p * sum(Pr[1,(1:l)])) * V[1, l] + 
    beta  *(1-delta) * p * sum((V[1,] * Pr[1,])[(l+1):300001])
  l = l + 1
}

If on *nix (Linux, Unix, macOS, ...) you can use parallel processing:

library(parallel)

VV <- matrix(ncol = 300001)
mclapply(2:300001, function(l){
  VV[1,l] <<- log(b+(l-1) * 0.001-0.0005) + k + beta * (1-delta) * (1-p * sum(Pr[1,(1:l)])) * V[1,l]+beta  *(1-delta) * p * sum((V[1,] * Pr[1,])[(l+1):300001])
  }, mc.cores = 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM