有没有办法提高 Rs 速度(for-loop)?

Is there a way to improve Rs speed (for-loop)?

我正在使用基本的 for 循环,计算大约需要 10 分钟:

for (t in 2:outsample) {
  ugfit_sged <- ugarchfit(spec = ug_spec_sged, data = rIBM[1:(insample+t-1)])
  coef_sged[t,] <- coef(ugfit_sged)
}

幸运的是,我对结果很满意,但仍然很烦人的代码需要这么长时间。当我查看任务管理器时,我发现 RStudio 几乎不使用任何 CPU 或 RAM。这让我想知道这是否正常,或者是否有办法增加 CPU 的 Rs 使用率,我希望这会使其更快。

我用过:

startDate = as.Date("2007-01-03") #Specify period of time we are interested in
endDate = as.Date("2018-04-30")

insample <- 2500
outsample <- 350
T <- insample + outsample

#Package: Quantmod
getSymbols("IBM", from = startDate, to = endDate)
rIBM <- dailyReturn(IBM)

#Package: rugarch
ug_spec_sged <- ugarchspec(variance.model = list(model = "sGARCH", garchOrder = c(1,1)),
                          mean.model = list(armaOrder = c(1,0), include.mean = FALSE),
                          distribution.model = "sged")

coef_sged <- matrix(nrow = outsample, ncol = length(coef(ugfit_sged)))
colnames(coef_sged) <- names(coef(ugfit_sged))
rownames(coef_sged) <- c(1:outsample)
coef_sged[1,] <- coef(ugfit_sged)

看起来不太乐观。让我们测量一下:

system.time({for (t in 2:outsample) {
  ugfit_sged <- ugarchfit(spec = ug_spec_sged, data = rIBM[1:(insample+t-1)])
  coef_sged[t,] <- coef(ugfit_sged)
}})
#   user  system elapsed 
#431.305   0.108 432.105 
(431.305+0.108)/349
#[1] 1.23614

此处的一个循环周期花费了 1.2 多秒。

system.time({ugfit_sged <- ugarchfit(spec = ug_spec_sged, data = head(rIBM, insample+2-1))})
#   user  system elapsed 
#  1.191   0.000   1.195 

即使使用最短的数组切片,单次调用 ugarchfit 也需要将近 1.2 秒。所以,大部分时间都花在了ugarchfit里面;如果可能的话,任何重要的优化都必须在那里进行。循环开销可以忽略不计——毕竟它只有 349 次运行。

I've read that some packages allow for parallel computing. Do you think that could speed the process up a bit? (I haven't worked with parallel computing before)

我也没有(在 R 中),但使用 mclapply 可能相对简单……未经过彻底测试:

library(parallel)
system.time(mclapply(2:outsample, function(t) {
  ugfit_sged <- ugarchfit(spec = ug_spec_sged, data = rIBM[1:(insample+t-1)])
  coef_sged[t,] <- coef(ugfit_sged)
}, mc.cores=detectCores()))  # maybe you want to use fewer than all cores