问题描述
假设我有一组脚本,其中包含以下内容: 每个脚本都会打印到控制台“hello world”和脚本执行时间。
t0<- Sys.time()
print('hello world')
t1<- Sys.time()
time.taken<- round(as.numeric(t1-t0),2)
time.taken
cat(paste("\n[script1] -","Execution time: ",time.taken,"seconds"))
现在我正在尝试获取多个来源的时间执行:
source("modules/script1.R")
source("modules/script2.R")
source("modules/script3.R")
source("modules/script4.R")
source("modules/script5.R")
source("modules/script6.R")
然而,这将分别打印每个脚本的执行时间,而不是在环境中的控制台中, 在 R 环境中得到这样的东西会很棒:
#script execution time
#1 2 seconds
#2 2 seconds
#3 2 seconds
#4 2 seconds
#5 2 seconds
#6 2 seconds
这甚至可能吗? 有哪些资源可用于此类处理?
解决方法
您可以使用 Windows 上的 parLapply
或 mclapply
包中的 parallel
并行运行脚本。
脚本中计算出的最后一个值被传递给 source
函数。
如果你确定脚本的最后一个值是它的执行时间,它会被 list
作为一个 lapply
返回:
library(parallel)
l <- 1:6
# Create script files
createscript <- function(numscript) {
cat('
t0<- Sys.time()
print("hello world")
Sys.sleep(runif(1))
t1<- Sys.time()
time.taken<- round(as.numeric(t1-t0),2)
time.taken
print(paste("[script1] -","Execution time: ",time.taken,"seconds"))
data.frame(time.taken)',file =paste0("Script",numscript,".R"),append = F)
T
}
lapply(l,createscript)
# Scripts list
scripts <- paste0("Script",l,".R")
# Run scripts in parallel
cl <- makeCluster(getOption("cl.cores",detectCores() - 1))
result <- parLapply(cl,scripts,function(script) {source(script)$value})
do.call(rbind,result)
time.taken
1 0.87
2 0.51
3 0.61
4 0.38
5 0.37
6 0.91